Compare commits

..
16 Commits
Author SHA1 Message Date
lzstealth a4936b6a20 Keep empty region previews blank
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m14s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 32s
2026-09-14 00:22:39 +01:00
lzstealth 1e317997c4 Document time date placeholder transforms
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m15s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 35s
2026-09-14 00:07:49 +01:00
lzstealth 222162df57 Fix player cached images and blank time dates
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m50s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 33s
2026-09-13 23:56:08 +01:00
lzstealth ac18644fe8 Release 2.13.3 2026-09-13 23:47:11 +01:00
lzstealth fea29f6a3c Release v2.13.2
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m18s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 34s
2026-09-11 21:18:54 +01:00
lzstealth 394d23bb4d Release v2.13.1
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m15s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 32s
2026-09-11 20:46:37 +01:00
lzstealth 0a03cdd0b7 Release v2.12.0
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 2m6s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 33s
2026-09-11 17:22:31 +01:00
lzstealth bdb5ab4bac Release v2.11.3
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m46s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 31s
2026-09-08 17:06:53 +01:00
lzstealth c4ae69d25f release: v2.11.2
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 2m0s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 31s
2026-09-05 18:14:38 +01:00
lzstealth 7fec2154e0 fix: preserve settings during cleanup
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m17s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 31s
2026-09-04 22:16:43 +01:00
lzstealth 48c007f7b2 fix: add invitation template formatting controls
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m15s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 32s
2026-09-04 22:13:15 +01:00
lzstealth ed2f23bb5d docs: update deployment and API references 2026-09-04 21:39:28 +01:00
lzstealth 954e0edc3f Organize changelog entries 2026-09-04 16:04:15 +01:00
lzstealth 3dfa6ea164 Document remote player public URL 2026-09-04 15:47:48 +01:00
lzstealth 98f969ca0f Release v2.11.1
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile, web, pulse-signage-web) (push) Successful in 1m47s
Publish Docker Image / build-and-push-existing-registry (./build/Dockerfile.player, player, pulse-signage-player) (push) Successful in 31s
2026-09-04 15:43:55 +01:00
lzstealth 2c150b5b2e Adjust system settings save button 2026-08-29 15:07:18 +01:00
180 changed files with 8463 additions and 1027 deletions
+156 -32
View File
@@ -2,13 +2,125 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## 2.13.3 - 2026-09-13
### Fixed
- Fixed the template background image media picker Upload media button so it opens the file selector.
- Fixed the template designer empty background message moving when the background image is removed.
- Fixed cached API and RSS images not being served by the player after being downloaded.
- Fixed blank time/date regions displaying the default clock format on the player.
- Fixed the time/date placeholder popup omitting text and math transform help.
- Fixed empty region previews displaying type labels instead of remaining blank.
- Fixed empty weather regions displaying the default weather summary.
## 2.13.2 - 2026-09-11
### Changed
- Refined the Media Library upload flow with a compact Add media modal, clearer toolbar controls, full-height scrolling, and more obvious selection feedback for media that is already in use.
## 2.13.1 - 2026-09-11
### Added
- Added the shared Media Library to slide region controls and template editors, preserving existing media paths while providing safe private uploads, responsive four-row server-side batching, and card-only scrolling with Load more pagination.
### Changed
- Added a font preview column to the Managed fonts table so each uploaded font can be viewed in its own typeface.
- Updated the WYSIWYG editor, slide image/video/QR-code region controls, and template editors to use the shared Media Library.
- Improved image cropper loading feedback by showing a spinner and hiding the crop surface until the image editor is ready.
## 2.12.0 - 2026-09-11
### Added
- Added offline-capable Local Control for central users with `clients.allow`, scoped to each player and its connected clients, with responsive client actions, current slide titles, and live WebSocket updates for pause and blackout state changes.
- Added player-specific HTTP-only sessions, minimized cached authentication data with hashed usernames, immediate session and socket revocation when authorization changes, and login throttling after repeated failures.
- Added web-owned authorization synchronization: connected remote players refresh every fifteen minutes and receive the current authorization state immediately after reconnecting, while the configured local player is excluded from remote fanout.
## 2.11.3 - 2026-09-08
### Fixed
- Added the reload confirmation prompt to individual client actions in the mobile clients view.
## 2.11.2 - 2026-09-05
### Changed
- Refreshed the vendored AdminLTE assets to 4.9.1, including the print-layout fixes and extended palette updates.
- Added independently configurable verification, password-reset, and invitation email expiry periods, with an `[[expiry_time]]` template variable.
- Updated default account email templates with inline formatting, action buttons, and links, and improved rendering when both button and URL placeholders are used.
- Shortened user-agent labels across audit logs and account session lists, and removed red/green change highlighting from audit entries.
## 2.11.1 - 2026-09-02
### Added
- Secure administrator invitations that create accounts only after the recipient accepts the invitation.
- Configurable API progress-bar placeholders with AdminLTE and announcement palette colors, custom colors, striped and animated variants, and quoted numeric literals.
- An optional `textless` progress-bar modifier to hide the visible percentage while retaining progress accessibility metadata.
- Configurable progress-bar radius options including `square`, `pill`, `rounded`, and validated `radius(...)` values.
- Arithmetic API placeholder transforms for adding, subtracting, multiplying, and dividing numeric values.
- Time-based progress bars using start and end date/time fields to show elapsed timetable-item progress.
- Audit events for invitation sending and acceptance, email verification, password-reset requests, and account email changes.
- A pending invitations page with invitation-specific Read, Create, Delete, and Allow permissions.
- Invitation deletion and resend actions with confirmation prompts.
- An opt-in Weather audit category for weather-location changes and manually queued refreshes.
- Opt-in per-command Screen Controls auditing, with forward and back navigation grouped together and disabled by default.
- The pending invitations list now supports pagination, search, and sorting, with Users, Roles, and Invitations grouped under expandable User management navigation.
- API progress calculations now support object-wrapped amounts.
### Changed
- Updated the invitation registration page to show fields only for valid tokens, use the themed failure state for invalid links, and pre-fill the invited email and display name.
- Made the invited email visibly disabled, kept the display name editable and required, and aligned invitation actions with the existing user forms.
- Added bold, italic, and underline formatting controls to the user invitation email message template editor.
- Fixed application-settings cleanup SQL so media and icon saves preserve all supported settings and no longer fail with MariaDB placeholder errors.
- Updated API progress bars to inherit the surrounding WYSIWYG text size and text color, preserve rounded corners, and render consistently in the editor preview, player, and thumbnails.
## 2.11.0 - 2026-09-02
### Added
- Optional account emails with administrator verification bypass, email verification, password recovery, and confirmed email changes.
- SMTP configuration and mail delivery for account notifications.
- Autofill restrictions for Bitwarden, LastPass, and 1Password on account profile and new-password fields while preserving current-password autofill.
### Changed
- Updated account email templates and previews to support both line breaks and paragraph spacing.
## 2.10.7 - 2026-09-02
### Added
- API token authentication now reuses access tokens until their expiry and can renew them with a refresh token, including refresh-token rotation.
- API sources can configure a refresh URL, JSON request body, and refresh-token response path.
- Client status badges now show Live, Paused, and Blackout states in the responsive Connected clients view.
### Changed
- Reorganized the API source editor into compact Connection, Authentication, and Latest response cards, with authentication collapsed by default on edit pages.
- Redesigned the Connected clients page for responsive mobile cards with compact controls, expandable search, pairing access, two-line detail clamping, and aligned desktop screen-group controls.
### Fixed
- Fixed client screen moves from mobile cards so the next move disables the clients current screen group rather than its previous one.
- Removed unused Bootstrap Icons font preloads that triggered browser warnings on pages where icons were not rendered.
## 2.10.6 - 2026-08-29 ## 2.10.6 - 2026-08-29
### Added
- Playlist recovery now uses cached browser and server snapshots, reports offline status, and recovers after cached responses.
### Changed ### Changed
- Refactored the player runtime into focused animation, media, transition, command, playback, and rendering modules. - Refactored the player runtime into focused animation, media, transition, command, playback, and rendering modules.
- Improved player slide transitions and video playback by preloading media, preserving precise durations, pausing outgoing videos during crossfades, and deferring expensive post-render setup. - Improved player slide transitions and video playback by preloading media, preserving precise durations, pausing outgoing videos during crossfades, and deferring expensive post-render setup.
- Added resilient playlist recovery through cached browser and server snapshots, offline status reporting, and refresh handling that recovers after cached responses.
### Fixed ### Fixed
@@ -34,6 +146,11 @@ All notable changes to this project will be documented in this file.
## 2.10.3 - 2026-08-28 ## 2.10.3 - 2026-08-28
### Added
- Remote screens now poll periodically to recover from missed refresh commands after bridge reconnects.
- Screens now use cached playlist snapshots while the bridge or web service is temporarily unavailable.
### Fixed ### Fixed
- Fixed the weather edit preview so the daily forecast is shown initially, the 24-hour forecast is hidden until selected, and the redundant hourly heading is removed. - Fixed the weather edit preview so the daily forecast is shown initially, the 24-hour forecast is hidden until selected, and the redundant hourly heading is removed.
@@ -44,8 +161,6 @@ All notable changes to this project will be documented in this file.
- Fixed remote player heartbeats to update the central onboarding bindings for active browser clients without treating the physical player registry ID as a client binding. - Fixed remote player heartbeats to update the central onboarding bindings for active browser clients without treating the physical player registry ID as a client binding.
- Fixed targeted commands after browser reconnects by falling back to the stable client ID when a transient connection ID is stale. - Fixed targeted commands after browser reconnects by falling back to the stable client ID when a transient connection ID is stale.
- Fixed stale browser command connections remaining active indefinitely when the physical player heartbeat was still healthy. - Fixed stale browser command connections remaining active indefinitely when the physical player heartbeat was still healthy.
- Added periodic playlist polling so remote screens recover from missed refresh commands after bridge reconnects.
- Added cached playlist snapshots so screens can continue displaying their last known playlist while the bridge or web service is temporarily unavailable.
- Fixed media synchronization so generated player caches are excluded while remote image caches remain available to players. - Fixed media synchronization so generated player caches are excluded while remote image caches remain available to players.
- Fixed weather screen notifications so changes in the fetched data or the current forecast hour trigger a refresh. - Fixed weather screen notifications so changes in the fetched data or the current forecast hour trigger a refresh.
- Fixed player runtime script loading and slide rendering so region modules, transitions, and cached playlists initialize consistently. - Fixed player runtime script loading and slide rendering so region modules, transitions, and cached playlists initialize consistently.
@@ -54,39 +169,42 @@ All notable changes to this project will be documented in this file.
## 2.10.2 - 2026-08-28 ## 2.10.2 - 2026-08-28
### Added
- Onboarding client heartbeats are now persisted so records inactive for 24 hours can be pruned without relying on player connectivity after the fact.
### Fixed ### Fixed
- Fixed the weather forecast preview to show only its first-fetch message until a successful forecast is available. - Fixed the weather forecast preview to show only its first-fetch message until a successful forecast is available.
- Added persisted onboarding client heartbeats so records inactive for 24 hours can be pruned without relying on player connectivity after the fact.
## 2.10.1 - 2026-08-28 ## 2.10.1 - 2026-08-28
### Added ### Added
- Added linear gradient backgrounds to templates, including multiple colours and angle control. - Linear gradient backgrounds to templates, including multiple colours and angle control.
- Added a visual gradient stop editor with draggable stops, click-to-add support, and stop reordering. - A visual gradient stop editor with draggable stops, click-to-add support, and stop reordering.
## 2.10.0 - 2026-08-28 ## 2.10.0 - 2026-08-28
### Added ### Added
- Added secure kiosk onboarding with QR-first and manual pairing flows. - Secure kiosk onboarding with QR-first and manual pairing flows.
- Added browser-specific pairing sessions with expiring pairing codes. - Browser-specific pairing sessions with expiring pairing codes.
- Added circular QR presentation and a compatible QR scanner with decoder fallbacks. - Circular QR presentation and a compatible QR scanner with decoder fallbacks.
- Added responsive player onboarding and a post-pair option to connect another player. - Responsive player onboarding and a post-pair option to connect another player.
- Added stable player identity bindings for paired players and moved-client aliases. - Stable player identity bindings for paired players and moved-client aliases.
- Added per-tab client identities backed by browser session storage for commands, pairing, and screen moves. - Per-tab client identities backed by browser session storage for commands, pairing, and screen moves.
- Added RBAC protection for player pairing through the `pairing.allow` permission. - RBAC protection for player pairing through the `pairing.allow` permission.
- Added a dedicated web onboarding workflow for pairing and managing player setup. - A dedicated web onboarding workflow for pairing and managing player setup.
- Pairing entry points now appear in the dashboard and connected clients workflows.
- A mobile-friendly connected clients link is now shown after successful pairing.
- Player keyboard feedback now includes slide navigation, plus `P` pause/unpause and `B` blackout toggles.
### Changed ### Changed
- Restricted direct screen URLs to the player configured for the requested screen. - Restricted direct screen URLs to the player configured for the requested screen.
- Added pairing entry points to the dashboard and connected clients workflows.
- Made pairing QR codes easier to scan by encoding only the short pairing code. - Made pairing QR codes easier to scan by encoding only the short pairing code.
- Added a mobile-friendly connected clients link after successful pairing.
- Made connected-client controls and player pairing UI render independently according to their permissions. - Made connected-client controls and player pairing UI render independently according to their permissions.
- Added player keyboard feedback for slide navigation, plus `P` pause/unpause and `B` blackout toggles.
- Removed client identities from onboarding and screen-move URLs; authorized player data now loads after the tab identity handshake. - Removed client identities from onboarding and screen-move URLs; authorized player data now loads after the tab identity handshake.
- Updated connected-client commands and screen moves to resolve tab and registered-player identities reliably. - Updated connected-client commands and screen moves to resolve tab and registered-player identities reliably.
@@ -95,9 +213,10 @@ All notable changes to this project will be documented in this file.
### Added ### Added
- API sources, RSS feeds, and weather locations can be enabled or disabled without deleting their cached data. - API sources, RSS feeds, and weather locations can be enabled or disabled without deleting their cached data.
- Added Weather slide regions with current, daily, and hourly placeholders, date/time transforms, and Bootstrap weather icon transforms. - Weather slide regions with current, daily, and hourly placeholders, date/time transforms, and Bootstrap weather icon transforms.
- Added multiple saved weather locations with provider, coordinate, unit, and refresh settings. - Multiple saved weather locations with provider, coordinate, unit, and refresh settings.
- Added separate Allow permissions for manually refreshing API sources, RSS feeds, and weather locations. - Separate Allow permissions for manually refreshing API sources, RSS feeds, and weather locations.
- Announcement colour choices and player rendering now include the AdminLTE extended palette colours.
### Changed ### Changed
@@ -110,7 +229,6 @@ All notable changes to this project will be documented in this file.
- Startup data-source refreshes now respect each API, RSS, and weather source's configured repull interval. - Startup data-source refreshes now respect each API, RSS, and weather source's configured repull interval.
- RSS feeds now persist their last collection timestamp. - RSS feeds now persist their last collection timestamp.
- Refreshed the vendored AdminLTE assets to 4.8.5. - Refreshed the vendored AdminLTE assets to 4.8.5.
- Added AdminLTE extended palette colours to announcement colour choices and player rendering.
- Removed Digital Signage Subheading and top padding. - Removed Digital Signage Subheading and top padding.
- API and RSS source saves now preserve cached data without pulling; added explicit manual refresh actions. - API and RSS source saves now preserve cached data without pulling; added explicit manual refresh actions.
@@ -118,13 +236,16 @@ All notable changes to this project will be documented in this file.
### Added ### Added
- Added configurable JSON POST requests and two-step login-then-token authentication for API sources. - Configurable JSON POST requests and two-step login-then-token authentication for API sources.
## 2.8.6 - 2026-08-18 ## 2.8.6 - 2026-08-18
### Added
- URL fields now provide live validation with inline feedback and explicit HTTP or HTTPS scheme enforcement.
### Fixed ### Fixed
- Added live URL validation with inline feedback and explicit HTTP or HTTPS scheme enforcement for URL fields.
- Prevented Enter in slide editor inputs from implicitly saving the slide. - Prevented Enter in slide editor inputs from implicitly saving the slide.
- Collapsed nested API response JSON sections by default while keeping the root response visible. - Collapsed nested API response JSON sections by default while keeping the root response visible.
@@ -139,8 +260,8 @@ All notable changes to this project will be documented in this file.
### Added ### Added
- Added local caching for API and RSS image placeholders under `player-cache/remote-images` for offline player playback. - Local caching for API and RSS image placeholders under `player-cache/remote-images` for offline player playback.
- Added reconciliation of cached remote images so files no longer referenced by slides are removed. - Reconciliation of cached remote images so files no longer referenced by slides are removed.
### Fixed ### Fixed
@@ -152,8 +273,8 @@ All notable changes to this project will be documented in this file.
### Added ### Added
- Added API, RSS, Timetable, and Time / Date placeholder help panels with shared transform and date-token documentation. - API, RSS, Timetable, and Time / Date placeholder help panels with shared transform and date-token documentation.
- Added render-time API and RSS image placeholders with proportional sizing and preview-only bounding boxes. - Render-time API and RSS image placeholders with proportional sizing and preview-only bounding boxes.
### Changed ### Changed
@@ -198,6 +319,7 @@ All notable changes to this project will be documented in this file.
- A permissions-gated System Settings page for announcement icon suggestions, media upload limits and MIME types, session lifetime, and password-change policies. - A permissions-gated System Settings page for announcement icon suggestions, media upload limits and MIME types, session lifetime, and password-change policies.
- Configurable forced password changes for newly created users and administrator password resets. - Configurable forced password changes for newly created users and administrator password resets.
- The database foundation for key-based application settings, including typed defaults and validation. - The database foundation for key-based application settings, including typed defaults and validation.
- All tables now use numeric auto-increment identifiers while retaining natural or relationship keys as unique constraints.
### Changed ### Changed
@@ -212,7 +334,6 @@ All notable changes to this project will be documented in this file.
- Replaced password strength presets with customizable length, category, and character requirements. - Replaced password strength presets with customizable length, category, and character requirements.
- Session expiration now uses the configured system setting, and user and role administration is grouped under the Settings area. - Session expiration now uses the configured system setting, and user and role administration is grouped under the Settings area.
- Renamed the system settings permissions to the `system-settings.*` namespace and migrated existing role assignments. - Renamed the system settings permissions to the `system-settings.*` namespace and migrated existing role assignments.
- Added numeric auto-increment identifiers to every table and retained natural or relationship keys as unique constraints.
## 2.7.6 - 2026-08-15 ## 2.7.6 - 2026-08-15
@@ -510,7 +631,7 @@ All notable changes to this project will be documented in this file.
### Added ### Added
- Added branded Windows and Linux kiosk launcher downloads on the dashboard, with updated copy that explains the launcher behavior more clearly. - 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. - Kiosk launchers now start the browser in kiosk mode, suppress notifications for Chromium-based browsers, and use the correct Firefox kiosk flag.
@@ -808,13 +929,13 @@ All notable changes to this project will be documented in this file.
### Added ### Added
- Screen and dashboard player links now render the full player URL instead of only the player base host. - Screen and dashboard player links now render the full player URL instead of only the player base host.
- Notes near the singleton-player code paths to make the future multi-player migration work easier to revisit.
### Changed ### Changed
- The player registry now uses a singleton `d_players` row and `d_screens.player_id` points at that shared player record. - The player registry now uses a singleton `d_players` row and `d_screens.player_id` points at that shared player record.
- Player startup is now responsible for creating the shared player record, while onboarding and state polling no longer create extra player rows. - Player startup is now responsible for creating the shared player record, while onboarding and state polling no longer create extra player rows.
- The screen/player binding path was simplified so opening a screen binds it to the shared player record without trying to re-register the player. - The screen/player binding path was simplified so opening a screen binds it to the shared player record without trying to re-register the player.
- Added notes near the singleton-player code paths to make the future multi-player migration work easier to revisit.
- Managed fonts now have dedicated editor/player sync handling, including a scheduled font sweep, sorted font-family lists, the TinyMCE fullscreen button, and shared font stylesheet loading in the WYSIWYG editor. - Managed fonts now have dedicated editor/player sync handling, including a scheduled font sweep, sorted font-family lists, the TinyMCE fullscreen button, and shared font stylesheet loading in the WYSIWYG editor.
- Text and RSS region types now own their own default style and fallback behavior instead of relying on shared slide helper fallbacks. - Text and RSS region types now own their own default style and fallback behavior instead of relying on shared slide helper fallbacks.
- Image and video region handling was also pushed further into modular per-type modules, keeping their editor, preview, and player logic closer to the region itself instead of the shared slide helper layer. - Image and video region handling was also pushed further into modular per-type modules, keeping their editor, preview, and player logic closer to the region itself instead of the shared slide helper layer.
@@ -1087,9 +1208,12 @@ All notable changes to this project will be documented in this file.
## 1.3.3 - 2026-07-21 ## 1.3.3 - 2026-07-21
### Added
- The first round of modular admin-page work, including a shared admin route layer and refreshed dashboard/list rendering.
### Changed ### Changed
- Added the first round of modular admin-page work, including a shared admin route layer and refreshed dashboard/list rendering.
- Updated the admin shell styling and layout handling for the newer page structure. - Updated the admin shell styling and layout handling for the newer page structure.
- Adjusted package metadata and lockfile state to match the release. - Adjusted package metadata and lockfile state to match the release.
@@ -1175,4 +1299,4 @@ All notable changes to this project will be documented in this file.
### Fixed ### Fixed
- Initial release. - Initial release.
+5 -6
View File
@@ -25,15 +25,14 @@ It gives you one place to publish playlists, slides, announcements, and live upd
Docker Compose is the recommended way to deploy Pulse Signage. It keeps the web app, player, bridge, and database together in a predictable setup. Docker Compose is the recommended way to deploy Pulse Signage. It keeps the web app, player, bridge, and database together in a predictable setup.
If you want the details, start with the [Compose guide](docker-compose/README.md). For a complete installation, follow the [public stack setup](docker-compose/README.md#public-stack-setup). For screens on separate devices, use the [remote player setup](docker-compose/README.md#remote-player-setup).
## Docs ## Docs
- [Documentation home](docs/README.md) - the technical reference index. - [Documentation home](docs/README.md) - the index for user and technical guides.
- [API reference](docs/api.md) - the player HTTP surface and onboarding endpoints. - [User guides](docs/user/README.md) - dashboard workflows, publishing, players, and Local Control.
- [Database schema](docs/schema.md) - the tables and data model the app maintains. - [Technical guides](docs/technical/README.md) - API, database, and WebSocket references.
- [WebSocket reference](docs/websocket.md) - the live player and snapshot channels. - [Docker Compose guide](docker-compose/README.md) - deployment, service configuration, and remote-player setup.
- [Compose guide](docker-compose/README.md) - deployment options and service layout.
- [Changelog](CHANGELOG.md) - release history and notable changes. - [Changelog](CHANGELOG.md) - release history and notable changes.
## Explore The Docs ## Explore The Docs
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "pulse-signage-player", "name": "pulse-signage-player",
"version": "2.10.6", "version": "2.13.3",
"private": false, "private": false,
"description": "Pulse Signage player application bundle", "description": "Pulse Signage player application bundle",
"engines": { "engines": {
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "pulse-signage-web", "name": "pulse-signage-web",
"version": "2.10.6", "version": "2.13.3",
"private": false, "private": false,
"description": "Pulse Signage web and bridge application bundle", "description": "Pulse Signage web and bridge application bundle",
"engines": { "engines": {
@@ -18,6 +18,7 @@
"handlebars": "^4.7.8", "handlebars": "^4.7.8",
"multer": "^2.2.0", "multer": "^2.2.0",
"mysql2": "^3.23.3", "mysql2": "^3.23.3",
"nodemailer": "^9.1.1",
"puppeteer-core": "^25.7.0", "puppeteer-core": "^25.7.0",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"jsqr": "^1.4.0", "jsqr": "^1.4.0",
+1 -1
View File
@@ -8,7 +8,7 @@ PULSE_SIGNAGE_SHARED_SECRET=""
PLAYER_IDENTIFIER="player-remote" PLAYER_IDENTIFIER="player-remote"
# Optional URL used by the kiosk launcher when the remote player is directly reachable # Optional URL used by the kiosk launcher when the remote player is directly reachable
# PLAYER_PUBLIC_URL="http://remote-player.example.com:8081" PLAYER_PUBLIC_URL="http://remote-player.example.com:8081"
PLAYER_AGENT_RECONNECT_DELAY_MS=5000 PLAYER_AGENT_RECONNECT_DELAY_MS=5000
+112 -61
View File
@@ -2,6 +2,21 @@
This folder contains the Docker Compose definitions for Pulse Signage, including the public stack and the remote player stack. This folder contains the Docker Compose definitions for Pulse Signage, including the public stack and the remote player stack.
## Contents
- [Files](#files)
- [Stack Overview](#stack-overview)
- [Services](#services)
- [Environment Files](#environment-files)
- [Public Stack Setup](#public-stack-setup)
- [Remote Player Setup](#remote-player-setup)
- [Shared Secret](#shared-secret)
- [Ports](#ports)
- [Volumes](#volumes)
- [Networks](#networks)
- [Notes](#notes)
- [Deployment Checklist](#deployment-checklist)
## Files ## Files
- [docker-compose.yml](docker-compose.yml) - full public stack with web, player, player bridge, and MySQL. - [docker-compose.yml](docker-compose.yml) - full public stack with web, player, player bridge, and MySQL.
@@ -45,6 +60,8 @@ Key configuration:
- `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD` - `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD`
- `PULSE_SIGNAGE_SHARED_SECRET` - `PULSE_SIGNAGE_SHARED_SECRET`
- `WEB_PUBLIC_URL`
- `BRIDGE_INTERNAL_URL`
- `DEFAULT_ADMIN_USERNAME` - `DEFAULT_ADMIN_USERNAME`
- `DEFAULT_ADMIN_NAME` - `DEFAULT_ADMIN_NAME`
- `DEFAULT_ADMIN_PASSWORD` - `DEFAULT_ADMIN_PASSWORD`
@@ -62,11 +79,13 @@ Responsibilities:
Key configuration: Key configuration:
- `PLAYER_PUBLIC_URL`
- `PLAYER_INTERNAL_URL` - `PLAYER_INTERNAL_URL`
- `PLAYER_IDENTIFIER` - `PLAYER_IDENTIFIER`
- `BRIDGE_PUBLIC_URL` in remote mode - `BRIDGE_PUBLIC_URL` in remote mode
- `PULSE_SIGNAGE_SHARED_SECRET` - `PULSE_SIGNAGE_SHARED_SECRET`
- database settings in local mode - `WEB_PUBLIC_URL`
- `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD` in local mode
### `player-bridge` ### `player-bridge`
@@ -96,46 +115,106 @@ Responsibilities:
Key configuration: Key configuration:
- `MYSQL_DATABASE` - `DB_NAME`
- `MYSQL_USER` - `DB_USER`
- `MYSQL_PASSWORD` - `DB_PASSWORD`
- `MYSQL_ROOT_PASSWORD` - `MYSQL_ROOT_PASSWORD`
## Environment Files ## Environment Files
### `.env.example` | File | Used by | How it is loaded |
| --- | --- | --- |
| `.env.example` | Public stack | Copy to `.env`; Compose loads it automatically, or pass it with `--env-file`. |
| `.env.remote.example` | Published remote player | Copy to `.env.remote`; pass it with `--env-file .env.remote`. |
Use this file as a starting point for the public compose stack. The example files are templates. Copy the appropriate file, review its defaults, and replace secrets or placeholder URLs before deploying.
### Public stack: `.env.example`
Use this file as a starting point for the public Compose stack.
Important values: Important values:
- `PULSE_SIGNAGE_WEB_IMAGE` - image to run for the web app and bridge services, typically `.../pulse-signage-web:latest` | Variable | Purpose | Default |
- `PULSE_SIGNAGE_PLAYER_IMAGE` - image to run for the player services, typically `.../pulse-signage-player:latest` | --- | --- | --- |
- `PULSE_SIGNAGE_SHARED_SECRET` - long random secret shared by the web, player, and bridge services for authenticated requests | `PULSE_SIGNAGE_WEB_IMAGE` | Image for the web app and bridge services. | `git.lzstealth.com/lzstealth/pulse-signage-web:latest` |
- `DB_*` - MySQL credentials and database name for the stack | `PULSE_SIGNAGE_PLAYER_IMAGE` | Image for the player services. | `git.lzstealth.com/lzstealth/pulse-signage-player:latest` |
- `MYSQL_ROOT_PASSWORD` - root password for the local MySQL container | `PULSE_SIGNAGE_SHARED_SECRET` | Shared request-signing secret. | Blank; set this for a secured deployment. |
- `WEB_PUBLIC_URL` - public URL of the web application | `DB_HOST` | MySQL host name. | `mysql` |
- `WEB_INTERNAL_URL` - internal URL the bridge uses to call the web app directly | `DB_PORT` | MySQL port. | `3306` |
- `PLAYER_IDENTIFIER` - unique local player identifier | `DB_NAME` | MySQL database name. | `pulse-signage` |
- `PLAYER_PUBLIC_URL` - URL used by the kiosk launcher and direct player access | `DB_USER` | MySQL user name. | `pulse-signage` |
- `PLAYER_INTERNAL_URL` - internal URL the web app uses for local player calls | `DB_PASSWORD` | MySQL user password. | `signage_password` |
- `BRIDGE_INTERNAL_URL` - bridge URL the web app uses for player snapshot and command forwarding | `MYSQL_ROOT_PASSWORD` | Local MySQL root password. | `root_password` |
- `DEFAULT_ADMIN_*` - bootstrap admin account values | `WEB_PUBLIC_URL` | Public URL of the web application. | `http://localhost:8080` |
| `WEB_INTERNAL_URL` | Internal URL the bridge uses to call the web app. | `http://web:8080` |
| `PLAYER_INTERNAL_URL` | Internal URL used for local player calls. | `http://player:8081` |
| `PLAYER_IDENTIFIER` | Unique local player identifier. | `player-local` |
| `PLAYER_PUBLIC_URL` | URL used by the kiosk launcher and direct player access. | `http://localhost:8081` |
| `BRIDGE_INTERNAL_URL` | Bridge URL used for snapshots and command forwarding. | `http://player-bridge:8090` |
| `DEFAULT_ADMIN_USERNAME` | Bootstrap admin username. | `admin` |
| `DEFAULT_ADMIN_NAME` | Bootstrap admin display name. | `Admin` |
| `DEFAULT_ADMIN_PASSWORD` | Bootstrap admin password. | `password123!` |
### `.env.remote.example` ### Remote player: `.env.remote.example`
Use this file on a remote player device. Use this file as the starting point for a remote player device. The production remote Compose file reads values from Compose's environment, so pass the copied file explicitly with `--env-file`.
Important values: Important values:
- `PULSE_SIGNAGE_PLAYER_IMAGE` - image to run on the device, typically `.../pulse-signage-player:latest` | Variable | Purpose | Default |
- `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 | `PULSE_SIGNAGE_PLAYER_IMAGE` | Image to run on the device. | `git.lzstealth.com/lzstealth/pulse-signage-player:latest` |
- `PLAYER_PUBLIC_URL` - optional URL used by the kiosk launcher when the remote player is directly reachable | `PULSE_SIGNAGE_SHARED_SECRET` | Shared request-signing secret; must match the public stack. | Blank; set it to the public stack's secret. |
- `BRIDGE_PUBLIC_URL` - bridge URL the player connects back to | `PLAYER_IDENTIFIER` | Unique remote player identifier. | `player-remote` |
- `PLAYER_AGENT_RECONNECT_DELAY_MS` - reconnect delay for the player agent | `PLAYER_PUBLIC_URL` | Optional URL for direct player access. | `http://remote-player.example.com:8081` |
| `BRIDGE_PUBLIC_URL` | Bridge URL the player connects back to. | `http://player-bridge.example.com:8090`; replace this placeholder. |
| `PLAYER_AGENT_RECONNECT_DELAY_MS` | Delay before reconnecting to the bridge. | `5000` |
### `PULSE_SIGNAGE_SHARED_SECRET` ## Public Stack Setup
Install Docker Engine with Docker Compose, then run the public stack from this directory:
```sh
cp .env.example .env
docker compose -f docker-compose.yml up -d
```
The command pulls the published images, creates the network and volumes, and starts the web app, local player, player bridge, and MySQL services. Check the installation with:
```sh
docker compose -f docker-compose.yml ps
docker compose -f docker-compose.yml logs -f web
```
## Remote Player Setup
A remote deployment has two parts:
- the public stack runs the web app, database, and player bridge
- each remote device runs only the player and connects back to the bridge
The remote player does not need database credentials. Set `BRIDGE_PUBLIC_URL` to the externally reachable bridge URL, including its port when required. It must point to the bridge service, not the web dashboard URL. The bridge must be reachable from the device and allow both HTTP requests and the player websocket connection at `/ws/players`.
### Published remote player
On the remote device:
```sh
cp .env.remote.example .env.remote
docker compose --env-file .env.remote -f docker-compose.remote.yml up -d
```
The published remote stack exposes the player on host port `8081`. Check its connection and startup output with:
```sh
docker compose --env-file .env.remote -f docker-compose.remote.yml ps
docker compose --env-file .env.remote -f docker-compose.remote.yml logs -f player
```
Start the public stack and confirm that its bridge is reachable before starting the remote player. Once the player connects, it should appear in the dashboard's Connected clients view. If it does not, verify the bridge URL, shared secret, firewall or reverse-proxy websocket support, and the player logs.
## 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. 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.
@@ -149,34 +228,6 @@ If you want a quick local value, generate one with a password manager or a comma
Leave it blank only if you intentionally want to run without request signing in a throwaway local setup. 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_WEB_IMAGE` | web, bridge | Docker image to run for the web app and bridge services. |
| `PULSE_SIGNAGE_PLAYER_IMAGE` | player, remote player | Docker image to run for the player 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. |
| `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. |
| `WEB_PUBLIC_URL` | web, player-bridge | Public URL of the web application. |
| `WEB_INTERNAL_URL` | player-bridge | Internal web URL used by the bridge to call the dashboard app directly. |
| `PLAYER_IDENTIFIER` | player | Stable player identifier. |
| `PLAYER_PUBLIC_URL` | player, remote player | URL used by the kiosk launcher and direct player access; optional for bridge-only remote players. |
| `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. |
| `DEFAULT_ADMIN_USERNAME` | web | Bootstrap admin username. |
| `DEFAULT_ADMIN_NAME` | web | Bootstrap admin display name. |
| `DEFAULT_ADMIN_PASSWORD` | web | Bootstrap admin password. |
| `BRIDGE_PUBLIC_URL` | remote player | URL of the bridge service. |
| `PLAYER_AGENT_RECONNECT_DELAY_MS` | remote player | Delay before reconnecting to the bridge. |
## Ports ## Ports
Public stack ports: Public stack ports:
@@ -210,16 +261,16 @@ Each compose file creates its own named network:
## Notes ## Notes
- The public stack expects the app services and MySQL to share the same `PULSE_SIGNAGE_SHARED_SECRET`. - The public stack expects the web, player, and bridge services 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. - 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 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 remote player should point `BRIDGE_PUBLIC_URL` at the bridge, not at the public web endpoint.
- The `PULSE_SIGNAGE_WEB_IMAGE` and `PULSE_SIGNAGE_PLAYER_IMAGE` tags default to the published `pulse-signage-web` and `pulse-signage-player` repositories with `latest` tags, but they can be overridden for custom releases. - The `PULSE_SIGNAGE_WEB_IMAGE` and `PULSE_SIGNAGE_PLAYER_IMAGE` tags default to the published `pulse-signage-web` and `pulse-signage-player` repositories with `latest` tags, but they can be overridden for custom releases.
## Recommended Setup ## Deployment Checklist
1. Copy `.env.example` to a local `.env` file for the public stack. 1. Follow [Public Stack Setup](#public-stack-setup) to start the public stack with Docker Compose.
2. Copy `.env.remote.example` to a device-specific `.env` file for the remote player. 2. Set the same `PULSE_SIGNAGE_SHARED_SECRET` in the public and remote environments.
3. Make sure `PULSE_SIGNAGE_SHARED_SECRET` matches everywhere. 3. Set `BRIDGE_PUBLIC_URL` to the externally reachable bridge URL.
4. Start the public stack first, then start the remote player after the bridge is reachable. 4. Start the published remote player with the workflow above.
5. Verify that the player appears in Connected clients before testing screen commands. 5. Verify that the player appears in Connected clients before testing screen commands.
+5 -5
View File
@@ -1,13 +1,13 @@
# Documentation # Documentation
This folder contains the technical reference material for Pulse Signage. This folder contains user guides and technical references for Pulse Signage.
## Whats Here ## Whats Here
- [API reference](api.md) - the player HTTP surface and onboarding endpoints. - [User guides](user/README.md) - using the dashboard, publishing content, operating players, and Local Control.
- [Database schema](schema.md) - the tables and data model used by the app. - [Technical guides](technical/README.md) - API, database, and WebSocket references.
- [WebSocket reference](websocket.md) - the live player and snapshot channels. - [Compose guide](../docker-compose/README.md) - Docker Compose deployment and service configuration.
## How To Read It ## 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. If you want the big picture first, start with the main [project README](../README.md). Use the user guides for everyday work and the technical guides for integration, deployment, and maintenance.
+9
View File
@@ -0,0 +1,9 @@
# Technical Guides
These references describe the service interfaces and internal data model used to integrate with, deploy, and maintain Pulse Signage.
- [API reference](api.md) - player HTTP endpoints and onboarding integration.
- [Database schema](schema.md) - application tables and relationships.
- [WebSocket reference](websocket.md) - player control and snapshot channels.
For service configuration and deployment, see the [Compose guide](../../docker-compose/README.md).
+74 -15
View File
@@ -6,7 +6,7 @@ Player service base URL: `http://localhost:8081`
This document covers the player HTTP surface only. The admin dashboard exposes its own routes for screen commands and onboarding management. This document covers the player HTTP surface only. The admin dashboard exposes its own routes for screen commands and onboarding management.
Access note: most player endpoints are unauthenticated because they are meant to run inside a trusted deployment network. Anything that mutates state or writes files should be treated as internal-only unless you add your own auth layer in front of it. Pairing uses a short-lived random PIN displayed by the kiosk; the PIN is accepted only through the authenticated Web UI pairing flow. Access note: when `PULSE_SIGNAGE_SHARED_SECRET` is set, player-page endpoints require a valid `x-pulse-page-auth` token with the appropriate scope, and server-to-server endpoints require the signed request headers. When the secret is unset, these checks are disabled for compatibility, so the player service should remain inside a trusted deployment network. Pairing uses a short-lived random PIN displayed by the kiosk; the PIN is accepted only through the authenticated Web UI pairing flow.
When `PULSE_SIGNAGE_SHARED_SECRET` is set, the player pages sign same-origin API fetches with `x-pulse-page-auth`, and the web app signs server-to-player requests with `x-pulse-request-timestamp` plus `x-pulse-request-signature`. Page tokens auto-renew before expiry while the page stays active, and signed server requests are only accepted when their timestamp is fresh. If the secret is unset, those checks stay disabled for compatibility. When `PULSE_SIGNAGE_SHARED_SECRET` is set, the player pages sign same-origin API fetches with `x-pulse-page-auth`, and the web app signs server-to-player requests with `x-pulse-request-timestamp` plus `x-pulse-request-signature`. Page tokens auto-renew before expiry while the page stays active, and signed server requests are only accepted when their timestamp is fresh. If the secret is unset, those checks stay disabled for compatibility.
@@ -26,23 +26,50 @@ Access: the configured player may load only its persisted paired screen. An unpa
### `GET /api/onboarding/status` ### `GET /api/onboarding/status`
Returns the persisted onboarding status for a device. Returns the persisted onboarding status for a device.
Access: public within the trusted player deployment. Access: requires a page-auth token with the `onboarding` or `player` scope when shared-secret authentication is enabled.
Query fields: Query fields:
- `deviceId` required - `deviceId` optional; the player device ID is used when omitted
### `GET /api/onboarding/screens` ### `GET /api/onboarding/screens`
Returns the list of screens available for onboarding. Returns the list of screens available for onboarding.
Access: public within the trusted player deployment. Access: requires a page-auth token with the `onboarding` scope when shared-secret authentication is enabled.
### `GET /api/onboarding/qr` ### `GET /api/onboarding/qr`
Returns an SVG QR code that points to the onboarding form. Returns an SVG QR code that points to the onboarding form.
Access: public within the trusted player deployment. Access: public on the player service; the bridge version requires a signed server request when shared-secret authentication is enabled.
Query fields: Query fields:
- `deviceId` required - `deviceId` optional; the player device ID is used when omitted
### `GET /api/onboarding/resolve`
Resolves a short-lived kiosk pairing code to its device and client identifiers.
Access: requires an onboarding page token or signed server request when shared-secret authentication is enabled.
Query fields:
- `pairingCode` required
Response fields:
- `deviceId`
- `clientId`
### `GET /api/onboarding/session`
Returns the current pairing session for the player page.
Access: requires an onboarding page-auth token when shared-secret authentication is enabled.
Query fields:
- `deviceId` optional
- `clientId` optional
Response fields:
- `deviceId`
- `pairingCode`
### `POST /api/auth/page` ### `POST /api/auth/page`
Renews the current page-auth token before it expires. Renews the current page-auth token before it expires.
@@ -54,15 +81,28 @@ Response fields:
- `issuedAt` - `issuedAt`
- `expiresAt` - `expiresAt`
### `POST /api/screen-move-authorize`
Stores a short-lived screen-move authorization token in an HTTP-only cookie.
Access: requires a valid screen-move page-auth token in the request body.
Accepted request fields:
- `moveToken` required
Response fields:
- `ok`
### `POST /api/onboarding` ### `POST /api/onboarding`
Binds a device to a screen and client name. Binds a device to a screen and client name.
Access: internal-only. Browser submissions must go through the authenticated Web UI pairing page. The Web UI resolves the short-lived kiosk PIN to a device ID before forwarding the signed request. Protect this endpoint if the player service is reachable outside your trusted network. Access: internal-only. Requires an onboarding page-auth token or signed request when shared-secret authentication is enabled, plus a valid short-lived kiosk pairing code. Browser submissions must go through the authenticated Web UI pairing page.
Accepted request fields: Accepted request fields:
- `deviceId` required
- `clientName` required - `clientName` required
- `screenSlug` required - `screenSlug` required
- `pairingCode` required
- `clientId` required
Response fields: Response fields:
@@ -76,7 +116,7 @@ Response fields:
### `GET /api/media/config` ### `GET /api/media/config`
Returns the upload directory configured for the player service. Returns the upload directory configured for the player service.
Access: internal-only. Access: internal-only and requires signed request headers when shared-secret authentication is enabled.
Response fields: Response fields:
@@ -85,15 +125,15 @@ Response fields:
### `PUT /api/media/{filename}` ### `PUT /api/media/{filename}`
Writes an uploaded file into the player upload directory. Writes an uploaded file into the player upload directory.
Access: internal-only and write-protected behind your deployment boundary. Access: internal-only and requires signed request headers when shared-secret authentication is enabled.
### `DELETE /api/media/{filename}` ### `DELETE /api/media/{filename}`
Deletes a file from the player upload directory. Deletes a file from the player upload directory.
Access: internal-only and write-protected behind your deployment boundary. Access: internal-only and requires signed request headers when shared-secret authentication is enabled.
### `GET /api/rtmp/session` ### `GET /api/rtmp/session`
Creates or reuses an RTMP-to-HLS session for a source URL. Creates or reuses an RTMP-to-HLS session for a source URL.
Access: internal-only. Access: requires a page-auth token with the `player` scope when shared-secret authentication is enabled.
Query fields: Query fields:
@@ -118,7 +158,7 @@ Access: internal-only.
### `GET /api/screens/{slug}/playlist` ### `GET /api/screens/{slug}/playlist`
Returns the current playlist payload for a screen. Returns the current playlist payload for a screen.
Access: public within the trusted player deployment. Access: requires a page-auth token with the `player` scope when shared-secret authentication is enabled. The player also checks that the browser is authorized for the requested screen.
Response fields: Response fields:
@@ -130,10 +170,19 @@ Response fields:
- `timetableGroups` - `timetableGroups`
- `revision` - `revision`
### `GET /api/screens/{slug}/announcement`
Returns the active announcement for a screen.
Access: requires a page-auth token with the `player` scope when shared-secret authentication is enabled. The player also checks that the browser is authorized for the requested screen.
Response fields:
- `announcement`
- `revision`
### `GET /api/screens/{slug}/connections` ### `GET /api/screens/{slug}/connections`
### `GET /api/screens/{slug}/clients` ### `GET /api/screens/{slug}/clients`
Returns the live player connection snapshot for a screen. Returns the live player connection snapshot for a screen.
Access: public within the trusted player deployment, but it exposes live connection state. Access: internal-only and requires signed request headers when shared-secret authentication is enabled; it exposes live connection state.
Response fields: Response fields:
@@ -143,9 +192,19 @@ Response fields:
- `connections` - `connections`
- `degraded` - `degraded`
### `POST /api/screens/{slug}/announcements/refresh`
Notifies connected players that the active announcement should be refreshed.
Access: internal-only and requires signed request headers when shared-secret authentication is enabled.
Response fields:
- `ok`
- `screenSlug`
- `sent`
### `POST /api/screens/{slug}/commands` ### `POST /api/screens/{slug}/commands`
Sends a command to the player connections for a screen. Sends a command to the player connections for a screen.
Access: internal-only. The admin dashboard should remain the protected control surface for commands. Access: internal-only and requires signed request headers when shared-secret authentication is enabled. The admin dashboard should remain the protected control surface for commands.
Accepted request fields: Accepted request fields:
+53 -9
View File
@@ -13,12 +13,34 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
- `a_role_permissions` - many-to-many mapping between roles and permissions. - `a_role_permissions` - many-to-many mapping between roles and permissions.
- `a_user_roles` - many-to-many mapping between users and roles. - `a_user_roles` - many-to-many mapping between users and roles.
- `a_sessions` - persisted admin session tokens. - `a_sessions` - persisted admin session tokens.
- `a_account_tokens` - short-lived account verification and password-reset tokens.
- `a_user_invitations` - pending user invitations and assigned role ids.
- `a_login_attempts` - login rate-limit and lockout state.
### `a_users` ### `a_users`
- `id`, `name`, `username`, `password_hash`, `password_salt`, `password_iterations`, `must_change_password`, `account_locked`, `created_at`, `created_by`, `modified_at`, `modified_by` - `id`, `name`, `username`, `email`, `email_verified_at`, `pending_email`, `pending_email_token_hash`, `pending_email_expires_at`, `password_hash`, `password_salt`, `password_iterations`, `must_change_password`, `account_locked`, `last_login_at`, `last_login_ip`, `created_at`, `created_by`, `modified_at`, `modified_by`
- `username` is unique. - `username` is unique.
### `a_account_tokens`
- `id`, `user_id`, `token_type`, `token_hash`, `expires_at`, `used_at`, `created_at`
- `token_hash` is unique.
- Foreign key:
- `user_id` -> `a_users.id` with `ON DELETE CASCADE`
- Indexed by `(token_type, token_hash, expires_at)` and `(user_id, token_type)`.
### `a_user_invitations`
- `id`, `email`, `name`, `role_ids_json`, `token_hash`, `expires_at`, `used_at`, `created_at`, `created_by`
- `token_hash` is unique.
- Indexed by `(email, used_at, expires_at)` and `(created_by, created_at)`.
### `a_login_attempts`
- `id`, `rate_key`, `failed_count`, `last_failed_at`, `locked_until`, `created_at`, `modified_at`
- `rate_key` is unique.
### `a_roles` ### `a_roles`
- `id`, `role_key`, `name`, `description`, `created_at`, `created_by`, `modified_at`, `modified_by` - `id`, `role_key`, `name`, `description`, `created_at`, `created_by`, `modified_at`, `modified_by`
@@ -60,6 +82,7 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
- `c_templates` - slide templates with canvas and background settings. - `c_templates` - slide templates with canvas and background settings.
- `c_template_regions` - template region layout and metadata. - `c_template_regions` - template region layout and metadata.
- `c_slides` - slide records with template binding, JSON content, and thumbnail path. - `c_slides` - slide records with template binding, JSON content, and thumbnail path.
- `c_media_assets` - reusable uploaded media files referenced by slides and templates.
- `c_playlist_slides` - ordered playlist items and timing. - `c_playlist_slides` - ordered playlist items and timing.
- `c_playlist_slide_schedule_rules` - rule rows attached to playlist slides. - `c_playlist_slide_schedule_rules` - rule rows attached to playlist slides.
@@ -93,6 +116,12 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
- Foreign key: - Foreign key:
- `template_id` -> `c_templates.id` with `ON DELETE SET NULL` - `template_id` -> `c_templates.id` with `ON DELETE SET NULL`
### `c_media_assets`
- `id`, `media_path`, `original_name`, `media_type`, `mime_type`, `file_size`, `is_published`, `created_at`, `created_by`, `modified_at`, `modified_by`
- `media_path` is unique.
- Indexed by `media_type` and `created_at`.
### `c_playlist_slides` ### `c_playlist_slides`
- `id`, `playlist_id`, `slide_id`, `position`, `duration_seconds`, `use_video_duration`, `disable_audio`, `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`
@@ -134,7 +163,7 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
### `d_onboarding_devices` ### `d_onboarding_devices`
- `id`, `device_id`, `client_name`, `screen_id`, `created_at`, `created_by`, `modified_at`, `modified_by` - `id`, `device_id`, `client_name`, `screen_id`, `created_at`, `created_by`, `modified_at`, `modified_by`, `last_seen_at`
- `device_id` is unique. - `device_id` is unique.
- Foreign key: - Foreign key:
- `screen_id` -> `d_screens.id` with `ON DELETE SET NULL` - `screen_id` -> `d_screens.id` with `ON DELETE SET NULL`
@@ -166,6 +195,7 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
- `i_rss_feeds` - RSS feed definitions and refresh cadence. - `i_rss_feeds` - RSS feed definitions and refresh cadence.
- `i_rss_feed_items` - cached RSS feed items. - `i_rss_feed_items` - cached RSS feed items.
- `i_api_sources` - API source definitions and last response snapshot. - `i_api_sources` - API source definitions and last response snapshot.
- `i_weather_locations` - configured weather locations and last response snapshot.
- `i_timetable_groups` - grouped timetable definitions used by the timetable region. - `i_timetable_groups` - grouped timetable definitions used by the timetable region.
- `i_timetable_entries` - dated entries that belong to a timetable group. - `i_timetable_entries` - dated entries that belong to a timetable group.
@@ -183,7 +213,7 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
### `i_api_sources` ### `i_api_sources`
- `id`, `name`, `api_url`, `auth_method`, `auth_username`, `auth_password`, `auth_bearer_token`, `auth_header_name`, `auth_header_value`, `items_path`, `update_interval_value`, `update_interval_unit`, `enabled`, `last_pulled_at`, `last_pull_error`, `last_response_status`, `last_response_content_type`, `last_response_json`, `created_at`, `created_by`, `modified_at`, `modified_by` - `id`, `name`, `api_url`, `auth_method`, `auth_username`, `auth_password`, `auth_bearer_token`, `auth_header_name`, `auth_header_value`, `token_url`, `token_request_body_json`, `token_response_path`, `token_refresh_url`, `token_refresh_request_body_json`, `token_refresh_response_path`, `token_header_name`, `token_header_prefix`, `items_path`, `update_interval_value`, `update_interval_unit`, `enabled`, `last_pulled_at`, `last_pull_error`, `last_response_status`, `last_response_content_type`, `last_response_json`, `created_at`, `created_by`, `modified_at`, `modified_by`
### `i_weather_locations` ### `i_weather_locations`
@@ -237,6 +267,7 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
- The schema is initialized with `CREATE TABLE IF NOT EXISTS`, so new installs can start from an empty database. - The schema is initialized with `CREATE TABLE IF NOT EXISTS`, so new installs can start from an empty database.
- `src/db/bootstrap.js` seeds the canvas size defaults, default permissions, and the default administrator role. - `src/db/bootstrap.js` seeds the canvas size defaults, default permissions, and the default administrator role.
- `src/db/migrations.js` records the current schema version in `o_app_state` during startup so later launches can tell whether an update is happening. - `src/db/migrations.js` records the current schema version in `o_app_state` during startup so later launches can tell whether an update is happening.
- The ER diagram shows declared foreign keys and the logical audit actor association; player registry and JSON-based references are intentionally not shown as foreign-key relationships.
```mermaid ```mermaid
erDiagram erDiagram
@@ -252,6 +283,12 @@ erDiagram
} }
A_SESSIONS { A_SESSIONS {
} }
A_ACCOUNT_TOKENS {
}
A_USER_INVITATIONS {
}
A_LOGIN_ATTEMPTS {
}
C_CANVAS_SIZES { C_CANVAS_SIZES {
} }
C_PLAYLISTS { C_PLAYLISTS {
@@ -262,6 +299,8 @@ erDiagram
} }
C_SLIDES { C_SLIDES {
} }
C_MEDIA_ASSETS {
}
C_PLAYLIST_SLIDES { C_PLAYLIST_SLIDES {
} }
C_PLAYLIST_SLIDE_SCHEDULE_RULES { C_PLAYLIST_SLIDE_SCHEDULE_RULES {
@@ -282,6 +321,8 @@ erDiagram
} }
I_API_SOURCES { I_API_SOURCES {
} }
I_WEATHER_LOCATIONS {
}
I_TIMETABLE_GROUPS { I_TIMETABLE_GROUPS {
} }
I_TIMETABLE_ENTRIES { I_TIMETABLE_ENTRIES {
@@ -300,18 +341,21 @@ erDiagram
A_ROLES ||--o{ A_ROLE_PERMISSIONS : has A_ROLES ||--o{ A_ROLE_PERMISSIONS : has
A_PERMISSIONS ||--o{ A_ROLE_PERMISSIONS : granted_to A_PERMISSIONS ||--o{ A_ROLE_PERMISSIONS : granted_to
A_USERS ||--o{ A_SESSIONS : owns A_USERS ||--o{ A_SESSIONS : owns
A_USERS ||--o{ O_AUDIT_EVENTS : acts A_USERS ||--o{ A_ACCOUNT_TOKENS : has
A_USERS o|--o{ O_AUDIT_EVENTS : acts
C_CANVAS_SIZES ||--o{ C_TEMPLATES : used_by C_CANVAS_SIZES o|--o{ C_TEMPLATES : used_by
C_CANVAS_SIZES ||--o{ C_PLAYLISTS : used_by C_CANVAS_SIZES o|--o{ C_PLAYLISTS : used_by
C_TEMPLATES ||--o{ C_TEMPLATE_REGIONS : contains C_TEMPLATES ||--o{ C_TEMPLATE_REGIONS : contains
C_TEMPLATES ||--o{ C_SLIDES : used_by C_TEMPLATES o|--o{ C_SLIDES : used_by
C_MEDIA_ASSETS }o..o{ C_SLIDES : referenced_by
C_MEDIA_ASSETS o{..o| C_TEMPLATES : background_for
C_PLAYLISTS ||--o{ C_PLAYLIST_SLIDES : contains C_PLAYLISTS ||--o{ C_PLAYLIST_SLIDES : contains
C_SLIDES ||--o{ C_PLAYLIST_SLIDES : included_in C_SLIDES ||--o{ C_PLAYLIST_SLIDES : included_in
C_PLAYLIST_SLIDES ||--o{ C_PLAYLIST_SLIDE_SCHEDULE_RULES : has_rules C_PLAYLIST_SLIDES ||--o{ C_PLAYLIST_SLIDE_SCHEDULE_RULES : has_rules
C_PLAYLISTS ||--o{ D_SCREENS : uses C_PLAYLISTS o|--o{ D_SCREENS : uses
D_SCREENS ||--o{ D_ONBOARDING_DEVICES : binds D_SCREENS o|--o{ D_ONBOARDING_DEVICES : binds
D_ANNOUNCEMENTS ||--o{ D_ANNOUNCEMENT_SCREENS : targets D_ANNOUNCEMENTS ||--o{ D_ANNOUNCEMENT_SCREENS : targets
D_SCREENS ||--o{ D_ANNOUNCEMENT_SCREENS : receives D_SCREENS ||--o{ D_ANNOUNCEMENT_SCREENS : receives
+36
View File
@@ -0,0 +1,36 @@
# User Guides
These guides explain how to use Pulse Signage to create content, publish it to screens, monitor players, and operate displays.
- [Web guide](guide-web.md) - content creation, publishing, screens, players, and everyday web workflows.
- [Local Control guide](guide-local-control.md) - player-specific offline controls, synchronization, and troubleshooting.
- [Data Sources guide](guide-data-sources.md) - configuring, refreshing, and troubleshooting changing data.
- [Administration guide](guide-admin.md) - accounts and fonts.
## How Pulse Signage Fits Together
The main content objects have a simple relationship:
- A **template** defines the structure and appearance of a slide.
- A **slide** is a piece of finished content built from that structure.
- A **playlist** arranges slides into a sequence.
- A **screen** is the display destination for a playlist.
- A **player** runs the screen and reports its connected clients.
You can reuse a template across many slides, reuse a slide across many playlists, and change a playlist without rebuilding the slides inside it. This separation lets you update one part of a signage setup without recreating everything around it.
## Typical Publishing Workflow
For a new piece of signage, work through the application in this order:
1. Decide the screen size or aspect ratio and create a matching [canvas size](guide-web.md#canvas-sizes) if one does not already exist.
2. Choose an existing [slide template](guide-web.md#slide-templates), or create one when the design needs a new structure.
3. Build a [slide](guide-web.md#slides), add its content, and preview it at the intended size.
4. Add the slide to a [playlist](guide-web.md#playlists) and place it in the correct order.
5. Assign the playlist to a [screen](guide-web.md#screens).
6. Check [connected clients](guide-web.md#connected-clients) to confirm the player is online and displaying the expected content.
7. Use an [announcement](guide-web.md#announcements) or [data source](guide-web.md#data-sources) when the information needs to change independently of the playlist.
The web application is the main place where content and screen assignments are managed. Once a change is saved, the relevant players receive the updated state.
For deployment and service setup, see the [Compose guide](../../docker-compose/README.md).
+133
View File
@@ -0,0 +1,133 @@
# Administration Guide
This guide covers the administrative tasks that support a Pulse Signage deployment: managing accounts and installing fonts. Administrative changes can affect many users or designs, so confirm the target before saving or deleting anything.
## Accounts and Access
Your account determines which parts of the web application are available to you. Administrators can invite users, create or edit accounts, assign roles, reset passwords, and remove accounts that are no longer needed.
### Inviting a User
Use the invitation workflow when the person should create their own account:
1. Enter the recipient's email address and display name.
2. Select the roles the person should receive after accepting the invitation.
3. Send the invitation.
4. Ask the recipient to follow the invitation message and complete account setup.
Assign the smallest role set that allows the person to do their work. Review the selected roles before sending because the invitation applies them when the account is accepted. If there are no roles available, create a suitable role before sending the invitation.
### Managing Existing Users
The users page shows usernames, display names, roles, and account status. Use it to:
- Edit a user's name or assigned roles.
- Reset a password when the user cannot sign in.
- Delete an account that is no longer needed.
- Search the user list when the deployment has many accounts.
The current administrator account is protected from actions that would remove or accidentally disable the account being used. When access changes, the web application remains the authority; you do not need to create separate users on each player.
If you cannot see a feature or action described in the user guides, ask an administrator to check your account rather than assuming the feature is unavailable.
## Fonts
Managed fonts are uploaded once to the deployment and can then be enabled for the editor and players. They are separate from slide media and are intended for font-family choices in text and data regions.
### Adding a Font
The Fonts page accepts WOFF2, WOFF, TTF, and OTF files. Provide the family name used by the design, choose the font file, and upload it. Use a name that clearly identifies the family and weight when several variants are installed.
After uploading a font:
1. Confirm it appears in the managed-font list.
2. Enable it if it is disabled.
3. Select it in a text, RSS, timetable, weather, or other text-rendering region.
4. Preview the slide at the target canvas size.
5. Check a connected player after font synchronization.
Disable a font when it should no longer be offered without deleting it. A font that is still in use cannot be deleted until the templates or slides no longer depend on it. Removing a font can change line wrapping and the height of text, so check affected content after any font change.
## System Settings
System Settings controls defaults, integrations, upload policies, security behavior, and diagnostics for the deployment. Change these values deliberately because a single setting can affect new content, multiple data sources, or every player.
### Application Defaults
Application defaults provide starting values for new content and player behavior, including:
- Default slide duration.
- Whether slides fade between one another by default.
- Whether unavailable RTMP streams are skipped.
- Default announcement icon and duration.
- Default RSS and API refresh intervals.
Defaults help keep new content consistent. They do not necessarily rewrite values that were already set on an existing slide, playlist, announcement, or source. Check the affected feature after saving a default change.
### Media Uploads
Media upload settings control the maximum image, video, and rich-text image sizes, along with the allowed image and video MIME types. Keep these limits large enough for the intended displays but small enough to avoid unnecessary storage and synchronization time.
Changing allowed types or size limits affects future uploads and may not change files that are already referenced. Test an upload after changing the policy, then check a player can synchronize the resulting file.
### Icon Suggestions
Icon Suggestions controls which announcement icons appear first in the icon picker. Select up to 48 suggestions and reorder them so the icons used most often are easy to find. This changes the picker order, not the icon already saved on an existing announcement.
### Weather Providers
Weather Providers stores shared credentials for the configured weather services. A provider may work without an API key or may require one before it can be selected for a weather location. Configure the provider here before creating locations that depend on it, and avoid placing provider credentials in source names, slide content, or public documentation.
### Security and Sessions
Security and Sessions contains deployment-wide controls for authentication and session behavior. Review these settings when changing login policy, session lifetime, or security controls. Test the change with a non-administrator account where possible so an overly restrictive setting does not prevent normal users from working.
### Email Delivery and Templates
Email Delivery configures SMTP for messages such as password recovery and account verification. Check the SMTP host, port, security mode, and enabled state before relying on invitations or recovery emails.
Email Templates controls the messages sent by the application. Keep the wording clear and verify links and sender details after changing a template. Send a test invitation or recovery message when the deployment's email settings change.
### Audit Logging and Diagnostics
Audit Logging controls the recording of authentication, security, and session events. Diagnostics provide information useful when investigating application behavior or background work. Limit diagnostic changes to the period needed for investigation and review the resulting activity afterward.
## Background Tasks
Background Tasks shows queued work that runs in the web process. Tasks can be queued, running, completed, failed, or canceled. The list includes the task name, category, timestamps, source, and any error message.
Use the task search and status filters to find work for a particular source or operation. A failed task's error message is the first place to look when a refresh, synchronization, cleanup, or notification did not complete. Finished tasks can be cleared after they have been reviewed; clearing the list does not undo the work that completed.
When a task remains queued, check whether the web process is running and whether earlier work is blocking the queue. When a task fails repeatedly, fix the underlying source, credential, file, or service problem before running the operation again.
## Scheduled Tasks
Scheduled Tasks shows recurring work such as source refreshes, player synchronization, and cleanup. For each task, review its interval, next run, last run, last result, and source when available.
Use **Run now** when an administrator needs an immediate refresh or synchronization rather than waiting for the next scheduled run. Check the last result after it completes. A failed scheduled run can leave the source or player state unchanged even though the recurring task remains registered.
Scheduled tasks are service operations, not content settings. Change a source's own update interval when the source should refresh at a different cadence; use the scheduled-task page to inspect or manually trigger the registered operation.
## Audit Log
The Audit Log records authentication, security, session, and other important administrative events. Filter by category or event type, search by event, actor, or target, and review the time, source address, user agent, and recorded changes.
Use the audit log to answer questions such as:
- Who changed a user, setting, source, or player-related value?
- When did a login, session, or security event occur?
- Which value changed, and what was it before the change?
- Did an unexpected update come from the web application or another source?
Export filtered results when they need to be retained for an investigation or shared with an administrator. Treat exported logs as sensitive operational information because they can contain account and network details.
## Administrative Checks
Before making a broad change:
- Check which slides, templates, users, sources, players, or defaults will be affected.
- Confirm the replacement content or account has been tested.
- Review the audit log before and after sensitive changes.
- Review task status when a synchronization change takes longer than expected.
See the [Local Control guide](guide-local-control.md) for player-specific offline controls.
+100
View File
@@ -0,0 +1,100 @@
# Data Sources Guide
Data sources let slides show information that changes without requiring someone to edit the slide each time. Configure a source once, allow it to refresh on its schedule, and use the current values in the appropriate slide region.
The source page is where you configure and test the connection or data. The template and slide editors are where you decide how that data appears on screen.
## Choosing a Source
Use the source type that matches the data you need:
- **RSS feeds:** headlines and other syndicated feed content.
- **API sources:** JSON data returned by a configured web service.
- **Timetables:** schedules made from named groups and entries.
- **Weather locations:** current or forecast weather for a saved location.
Create separate sources when the refresh cadence, authentication, location, or presentation needs are different. Give each source a clear name that identifies its purpose rather than only its URL.
## RSS Feeds
An RSS feed needs a name, a feed URL, an update interval, and the number of items to pull. The latest pulled items are shown on the feed page so you can verify the title, link, publication date, description, author, identifier, and comments fields before using them in a slide.
Use the item limit to keep the stored feed focused on the number of recent items your slides need. If the feed contains more items than the limit, older or excess items are not useful for the source's slide regions.
When an RSS feed fails, open the latest-items preview and check the reported pull error. Confirm the URL returns an RSS or compatible feed, then use **Refresh now** after correcting the source.
## API Sources
An API source connects to a JSON endpoint and can use either GET or POST:
- **GET:** retrieve data directly from the API URL.
- **POST:** send a JSON request body with the request.
Use **Items path** when the records needed by a slide are nested inside the response. Enter a dot-separated path such as `items` or `results.data` to identify the array that should be treated as the source items.
API authentication supports:
- No authentication.
- Basic username and password authentication.
- A bearer token.
- An API key sent in a named header.
- A login-then-token flow for services that issue a token from a login request.
For a login-then-token source, configure the login URL, JSON login body, token response path, and token header. If the service supports token refresh, configure the refresh URL, refresh-token response path, refresh body, and token prefix as required by that service. Keep credentials and tokens out of slide content and request examples that will be shared with other users.
After a pull, review the latest response details, including the last-pulled time, HTTP status, content type, and stored JSON response. Use the response structure to choose the item number, items path, and fields used by an API region.
## Timetables
A timetable group contains the events that a timetable region displays. Configure:
- A group name and optional short description.
- The IANA time zone used by the group, such as `Europe/Berlin`.
- One or more entries with a title, optional description, start time, and optional end time.
Use the group timezone consistently with the people and screens that will read the schedule. An entry without an end time can represent an item with an open-ended or display-only start time. Remove old entries rather than leaving expired events mixed with current ones.
## Weather Locations
A weather location is a saved place that weather regions can use. Search for a town, city, or postcode and choose a result so the application fills the coordinates and timezone. Coordinates can be edited manually when the lookup result needs adjustment.
Configure the provider and display units for each location:
- Temperature: Celsius or Fahrenheit.
- Wind: km/h, mph, or m/s.
- Precipitation: millimetres or inches.
- Update interval: minutes or hours, within the available limits.
The weather page provides a current preview and forecast preview. Use them to confirm the location, units, and provider before adding the location to a slide. A provider that is unavailable because its service credentials are not configured cannot be selected until the deployment is set up for it.
## Using Sources in Slides
Configure the source before selecting it in a template or slide region. The available region types include RSS, API, Timetable, and Weather, as well as Time / Date for values based on a timezone.
When designing a data-backed region:
- Leave enough width and height for the longest expected value.
- Decide which item, field, or forecast mode the region should show.
- Use the preview to check missing values, long titles, dates, and line wrapping.
- Keep the playlist stable when the changing information belongs in a source rather than in slide text.
Changing a source can affect every slide and screen that uses it. Check the source's existing usage before changing its field structure or meaning.
## Refreshing Data
Each source has an update interval and unit. Available intervals depend on the source type; RSS and API sources support seconds, minutes, or hours, while weather locations use minutes or hours. A source can also be refreshed manually when you need the latest values immediately.
Use **Disable** when a source should stop updating temporarily without deleting its configuration. Re-enable it when the source is ready to be used again. Deleting a source is a larger change because regions that depend on it may no longer have current values.
## Troubleshooting
When a data-backed slide is stale or empty, check in this order:
1. Open the source page and check whether it is enabled.
2. Check the last refresh time, latest response, or preview data.
3. Use **Refresh now** and read any returned error.
4. Confirm the source URL, authentication, response format, or location coordinates.
5. Check the region's selected source, item, field, path, or forecast mode.
6. Confirm the player is connected and has received the refreshed state.
An online source with a successful response can still produce an empty region when the selected item or field no longer exists. An online source can also appear stale on a player that has not yet reconnected or refreshed.
+146
View File
@@ -0,0 +1,146 @@
# Local Control
Local Control is a small control page hosted by an individual player. It lets an authorized user operate the clients connected to that player when the main web application is unavailable or inconvenient to reach.
Open Local Control at:
```text
http://player-address:8081/local-control
```
Use the address and port exposed by the player in your deployment. Local Control controls only the player that served the page; it does not show or control every player in the installation.
## When To Use It
The normal web application remains the main place to manage content, screens, playlists, users, and player assignments. Local Control is for immediate, player-specific operations such as:
- Reloading a client that is stuck or displaying an old page.
- Moving to the previous or next slide while checking playback.
- Pausing or resuming a client.
- Temporarily blacking out a client or restoring its display.
- Checking which client is connected and what it is currently showing.
Use the web application when you need to change a playlist, edit a slide, send commands to several screen groups, pair a player, or manage the signage setup.
## Signing In
Local Control uses the central account information supplied by the web application. There are no separate player user accounts to create or manage.
Enter the same username and password used for the central web application. Email addresses are not accepted in place of the username. The player checks the cached authorization data before creating a local session.
The login session is stored in a player-specific, HTTP-only cookie. The cookie is limited to the Local Control path and uses `SameSite=Lax`, so it is not intended to be shared with another player or another part of the application.
### Failed Logins
Repeated failed attempts are temporarily throttled to slow down guessing:
- Five failed attempts are allowed within a fifteen-minute window.
- Further attempts are rejected with a temporary lockout response.
- The lockout lasts until the oldest failed attempt falls outside the window, so it can be less than fifteen minutes after the last failed attempt.
- A successful login clears the failed-attempt record for that username and client address.
- The limiter is held in memory on the player and resets if the player restarts.
The login response does not reveal whether a username exists. This keeps invalid usernames and incorrect passwords on the same authentication path.
## What You See
After signing in, Local Control shows the clients currently connected to the player. Each client row can include:
- The client name.
- The screen name.
- The current slide title, when available.
- The available action buttons.
- Pause or blackout state when the client is in one of those states.
If no clients are connected, the page remains available but there are no client actions to send. Connect or restart the player client, then reload the Local Control page to check again.
## Client Actions
Actions apply to the selected client only.
### Reload
Reloads the client page. Use this when the page is stale, an asset did not load, or a player-side display needs to restart without changing its content assignment.
### Previous and Next
Moves the selected client to the previous or next slide in its current playlist. These actions are useful for checking a playlist or temporarily moving past a slide without editing the playlist.
### Pause and Resume
Pauses the selected client on its current state. The same control resumes playback when the client is paused.
### Blackout and Restore
Temporarily hides the selected client's display without changing its playlist. The same control restores the display. Use blackout for short operational interruptions; use screen or playlist changes when the content assignment itself needs to change.
## Live Updates
Local Control opens an authenticated WebSocket after login. When the player reports a state change, the page can update the affected client row without a manual refresh.
Live state can include:
- Current slide title.
- Pause state.
- Blackout state.
- Client connection and disconnection changes.
If the live connection is interrupted, the page attempts to reconnect. The underlying player state and commands are still scoped to the local player. If a browser cannot use WebSockets, the page falls back to periodic state requests.
## Offline Authorization Cache
The web application is the source of Local Control authorization. To support player-specific operation when the web application cannot be reached, each player stores a small local cache containing only the information needed to verify an eligible login:
- A hashed username.
- A password hash.
- A password salt.
Plain usernames, email addresses, display names, user IDs, and password iteration settings are not stored in this cache.
Cached authorization is considered usable for up to 72 hours after the last successful synchronization. Once that period expires, Local Control rejects login attempts until the player receives a fresh synchronization.
The cache is written with restricted file permissions and is not intended to be edited manually. Editing it does not provide a supported way to create local users.
## Authorization Updates
Authorization is managed centrally by the web application and delivered to players through authenticated service connections.
- Connected remote players receive a scheduled refresh every fifteen minutes.
- A remote player receives the current authorization state immediately after it reconnects to the bridge.
- The configured local player is not included in the remote-player fanout because it is refreshed through its local service path.
- When the synchronized authorization changes, existing Local Control sessions on that player are closed.
- A user removed from central access cannot continue using an existing Local Control session after the change reaches the player.
A player that remains disconnected can continue using its last valid cache until the cache expires. Once it reconnects, it receives the current central state.
## Scope and Limitations
Local Control is intentionally narrower than the web application:
- It controls only clients connected to the current player.
- It does not edit slides, templates, playlists, screens, or announcements.
- It does not pair players or move clients between screen groups.
- It does not provide local user administration.
- It does not replace the web application as the source of content or authorization.
## Troubleshooting
### The login page says authorization is unavailable
The cached authorization is missing or older than 72 hours. Restore the player's connection to the web service or bridge and wait for synchronization to complete. Restarting the player does not create a fresh authorization cache.
### A correct password is rejected
Confirm that you are using the central username rather than an email address. If several failed attempts were made, wait for the temporary login throttle to expire. Also check whether the account's central access has changed.
### A client is not listed
Confirm that the client is connected to the player serving Local Control. A client connected to another player will appear only in that player's Local Control page. Check the player connection and reload the page after the client reconnects.
### An action reports that the client is unavailable
The client may have disconnected between the time the page loaded and the time the action was sent. Reload the page and check the current client list before trying again.
### Changes from the web application are not visible
Check that the player can reach the web application or bridge and that its registration connection is healthy. A disconnected player can use its existing cache temporarily, but it cannot receive central authorization changes until it reconnects.
+308
View File
@@ -0,0 +1,308 @@
# Web Guide
Pulse Signage brings content creation, publishing, screen management, and live operations into one web application. This guide explains what each area is for, how the areas work together, and when to use each one.
## Overview
### Dashboard
The dashboard is the starting point for everyday work. It summarizes the parts of the system that matter most when you are publishing or checking displays, including screens, playlists, slides, templates, and active clients.
Use the dashboard to:
- See whether the system has content ready to publish.
- Move quickly to the content or screen area that needs attention.
- Check high-level counts and current activity.
- Identify whether a display problem is likely to be content-related or connection-related.
The dashboard is an overview rather than a replacement for the detailed pages. Use the dedicated feature pages when you need to edit content or investigate a specific connection.
## Screens and Players
### Screens
A screen represents a display destination in Pulse Signage. It gives a playlist somewhere to play and provides the link between your content and a physical display.
When setting up a screen, choose a clear name and stable slug so other people can recognize it. Assign the playlist that should normally play there, then associate the screen with the appropriate player during setup.
Use the screen area when you need to:
- Add a new display destination.
- Change the playlist shown on a display.
- Review which player is associated with a screen.
- Update screen details after a display is moved or renamed.
- Remove a display that is no longer part of the signage setup.
If a screen exists but is not showing the expected content, first check its assigned playlist, then check the player and client status.
Keep screen names specific to their physical location or purpose. The screen assignment is the publishing boundary: changing the playlist changes what that destination plays, while reusing a playlist lets several screens share the same experience.
### Connected Clients
A connected client is an active browser or player connection reporting to a screen. A single screen can have more than one connection over time as players restart, browsers reconnect, or replacement devices come online.
The clients page helps you distinguish content problems from runtime problems. It shows information such as:
- The client name and screen group.
- The current slide title, when one is available.
- The client viewport size.
- When the connection was established or last updated.
- Whether the client is paused or blacked out.
From this page, available controls can reload a client, move to the previous or next slide, pause playback, or toggle blackout. Commands apply to the selected connection, so confirm the client and screen before sending one.
If a client is missing, check that the player is running and connected before changing the playlist. If the client is present but showing the wrong content, check the screen's playlist and the playlist order.
Use client information to separate three common problems:
- A missing client usually indicates a player, network, bridge, or pairing problem.
- A connected client showing the wrong slide usually indicates a screen assignment or playlist problem.
- A connected client showing a broken region usually indicates a slide value, asset, source, or external stream problem.
### Client Pairing and Remote Players
Pairing connects a player device to a screen or screen group. The web application pairing workflow uses the player's six-character PIN and a client name.
A typical setup is:
1. Start the web application, database, and player bridge.
2. Open the pairing workflow from the web application.
3. Read the six-character PIN shown by the player, or scan its QR code.
4. Enter a name that identifies the physical player, such as `Lobby player`.
5. Select the screen the player should display.
6. Connect the player and wait for the pairing confirmation.
7. Confirm the player appears among connected clients.
8. Assign or verify the playlist for the selected screen.
Use a new client name when pairing a replacement device so the client list remains understandable. If the PIN is rejected or expires, return to the player and start the pairing display again before retrying.
A local player can run alongside the main application, while a remote player connects back to the player bridge from another location. Remote players need a working connection to the bridge and the web service.
If a remote player does not appear:
- Check the bridge address and shared connection settings.
- Confirm firewall rules allow the required traffic.
- Confirm WebSocket traffic is allowed through any reverse proxy.
- Check that the player can resolve and reach the service from its network.
- Check the connected clients page after the player reconnects.
The web application remains the main control source. Screen assignments, player commands, media synchronization, fonts, and access updates are delivered to players through the service connections. A player being offline does not make it an independent administration surface; it receives the current state when it reconnects.
## Content
### Slide Templates
A slide template is a reusable design definition. It sets the canvas, background, regions, layout, and animation defaults that editors use when creating slides. A template defines the visual structure; a slide fills that structure with a particular message or set of values.
Templates are useful when you want consistency. For example, an event announcement template can give every editor the same title, date, image, and background fields without asking them to rebuild the layout each time.
#### Template Details and Canvas
When creating or editing a template:
- Give the template a descriptive name based on its purpose.
- Choose the canvas size that matches the target display orientation and resolution.
- Use a landscape canvas for wide screens, a portrait canvas for vertical displays, and a custom size when the hardware needs one.
- Treat the canvas as the coordinate system for every region. A layout made for one aspect ratio may need a separate template for another.
- Preview the template at the canvas size where it will be used before publishing it.
Existing templates may lock their canvas size after slides have been created from them. If the design needs a different aspect ratio, create a separate template rather than distorting a template that is already in use.
#### Backgrounds
The template background is behind every region. It can be built from:
- A solid background colour.
- An uploaded background image.
- A linear gradient with an adjustable angle and multiple colour stops.
Use an image for a branded or photographic background, a colour for a simple consistent surface, and a gradient when the design needs depth without another media asset. Keep important details away from region boundaries and check text contrast against the final background. Removing a background image does not remove the regions placed above it.
#### Regions and Layout
A region is a named area of the canvas that provides one content slot on a slide. Add a region, choose its type, give it a stable name, and place it on the canvas. Regions can overlap; the Z-Index determines which region is drawn in front when they do.
Each region has layout controls for:
- **X and Y:** the region's position on the canvas.
- **Width and Height:** the region's size.
- **Lock ratio:** an optional ratio such as `16:9` that keeps the shape consistent while resizing.
- **Z-Index:** the stacking order for overlapping regions.
- **Region name:** the stable field name used to identify the content slot.
Use names such as `headline`, `hero_image`, `event_time`, or `room_schedule` instead of generic names. Stable names make slides easier to edit and make template changes easier to understand. Keep regions large enough for their longest expected value; a region that fits a short title may clip a longer announcement.
#### Region Types
The available region types cover fixed content, uploaded media, live data, and external content:
- **Text:** rich text content with font family, font size, font colour, and normal editorial formatting. Use it for headings, labels, paragraphs, and other copy that editors change per slide.
- **Image:** an uploaded image in the media library. The editor supports PNG, JPG, GIF, WebP, and SVG images, with cropping to the region ratio when needed.
- **Video:** an uploaded MP4, WebM, or Ogg video. Videos preview in the region and loop during playback.
- **HTML:** HTML content rendered inside a sandboxed preview. Use it for controlled custom markup when an ordinary text region cannot express the design.
- **Webpage:** a URL displayed in an embedded webpage region. Use it for a page that should be shown inside the slide, and verify that the destination permits embedding.
- **QR Code:** a generated QR code with configurable code content and visual styling. Use it for links, tickets, instructions, or other information that viewers can scan.
- **RSS:** a selected RSS feed item. Choose the feed and item, then map the available feed fields into the region.
- **API:** a value from a configured API source. Select the source, identify the item or path when required, and use the returned value in the slide.
- **Timetable:** schedule information from configured timetable groups and entries. Use it for room bookings, events, departures, or other structured schedules.
- **Weather:** current or forecast weather for a configured location. Select the location and forecast mode, then format the region to leave room for changing values.
- **Time / Date:** a clock or date display using a chosen timezone. Use it for local time, event dates, or location-specific schedules.
- **RTMP:** a live RTMP stream URL. Use it for a live video source and check that the player can reach the stream from its network.
Live region types depend on their configured source. Configure the RSS feed, API source, timetable, weather location, or other source before trying to use it in a slide.
#### Region Animations
Animations are configured per region and are saved with the template. They have three independent phases:
- **Intro:** how the region enters when the slide starts.
- **Outro:** how the region leaves when the slide ends.
- **Attention seekers:** a repeating animation while the slide is visible, useful for drawing attention to a status, alert, or call to action.
The basic choices include fades, slides, zooms, and attention effects such as pulse, flash, bounce, shake, swing, and heartbeat. Choose **None** when movement would distract from the content. Use the advanced animation settings when the basic choices do not provide the required direction, speed, delay, duration, or repeat behaviour. The template preview can play the intro, outro, or attention animation so you can check the result before saving.
Avoid animating every region at once. Staggered or limited motion is easier to read, especially for information-heavy slides and live data.
When working with templates:
- Keep fields focused on the content an editor is expected to change.
- Consider existing slides before changing a template, because layout changes can affect every slide built from it.
- Create a separate template when two designs are conceptually different instead of forcing one template to handle unrelated layouts.
- Use the preview controls to check backgrounds, overlapping regions, text wrapping, media cropping, and animations together.
Templates provide structure; they do not decide which slides play or which screen receives them.
### Slides
A slide is an individual piece of signage content. It is normally created from a template, filled with content, previewed, and then placed into one or more playlists.
Slides can contain ordinary editorial content such as text, images, video, HTML, QR codes, and webpages, as well as content that changes over time through announcements or data sources. This lets a playlist remain stable while the information inside a slide stays current.
When filling a slide, work through each region in the template rather than trying to redesign the layout in the slide editor. Enter text in text regions, upload or select media in media regions, and choose configured sources in live-data regions. The template's region names and layout remain the reference for how the slide is intended to look.
For media regions, check the crop and aspect ratio before saving. For text and live data, check the longest likely value, line wrapping, font size, and contrast. For webpages and streams, confirm the player network can reach the external address.
A useful slide workflow is:
1. Select the template that matches the intended design.
2. Fill in the visible content and any optional fields.
3. Preview the slide at the target canvas size.
4. Check text wrapping, image cropping, animation, and contrast.
5. Save the slide and add it to a playlist.
6. Recheck the live client after publishing.
If a slide is reused in multiple playlists, an edit can affect every place where it appears. Create a separate slide when the content needs to vary between destinations.
### Playlists
A playlist is the sequence a screen plays. It controls which slides appear, the order in which they appear, how long they remain visible, and how transitions behave.
Use playlists to organize content by destination, audience, or purpose. A lobby playlist, for example, may combine welcome messages, schedules, announcements, and a repeating information slide without changing the underlying templates.
When editing a playlist:
- Add only the slides that belong to that display experience.
- Reorder slides to establish the intended viewing sequence.
- Review each slide's duration and the overall rhythm of the sequence.
- Configure transitions where a change in visual pacing is useful.
- Decide how unavailable streams should be handled if the playlist uses live media.
- Save the playlist before checking the player.
The order is significant: viewers see slides from top to bottom and then return to the beginning. Use longer durations for slides with more text or live data, and use shorter durations for simple notices. A transition changes how one slide gives way to the next; it does not change the region animations inside either slide.
A playlist change affects the screens using that playlist. A slide change can affect every playlist that includes that slide, so choose the object that matches the scope of the change you intend to make.
### Canvas Sizes
Canvas sizes describe the dimensions or aspect ratios a design is meant to use. They help templates and slides stay predictable when a display has a known resolution or orientation.
Create a canvas size when your organization has a recurring display format, such as a landscape lobby screen, a portrait information board, or a wide event display. Use a consistent name that makes the intended hardware obvious.
Before publishing a design, preview it at the target canvas size. A slide designed for a wide screen may need different spacing, font sizes, or image treatment on a portrait display.
## Data and Live Content
### Announcements
Announcements are messages that can be sent to selected screens without rebuilding a regular playlist. They are useful for temporary information such as room changes, service notices, event reminders, alerts, or time-sensitive instructions.
An announcement normally includes:
- The message or content to display.
- How long it should remain visible.
- Its visual treatment, such as color or icon.
- The screens that should receive it.
Use an announcement when the message is temporary or targeted. Use a playlist slide when the content is part of the normal repeating experience.
After changing an announcement, connected players receive a refresh and update their displayed state. If a target screen is offline, it will receive the current state when it reconnects and refreshes its content.
Before sending an announcement, verify the target screens and the expiry or display duration. A broad target selection can interrupt many displays at once. Keep urgent messages short enough to read in the available time and use the visual treatment consistently so viewers can distinguish an announcement from normal scheduled content.
### Data Sources
See the [Data Sources guide](guide-data-sources.md) for supported source types, refresh behavior, and troubleshooting.
## Media
Media is added where it is needed in a template or slide. Image and video regions provide their own upload controls, while template backgrounds are uploaded from the template options. An upload in one slide or template is not automatically a reusable selection in every other slide, so add the file to each region or template where it is required.
### Images
Images can be used as template backgrounds or as content in image regions. Supported image formats are PNG, JPG, GIF, WebP, and SVG, subject to the deployment's upload policy.
When adding an image:
- Choose a file that suits the target canvas size and region shape.
- Keep important subjects away from the edges when the region may crop the image.
- Check the crop and scaling in the slide preview before publishing.
- Use a transparent PNG or SVG when the design needs the background to show through.
- Remember that animated image formats may be altered if they are cropped or transformed.
### Videos
Videos can be uploaded into video regions and used in playlists that support live media. The editor accepts MP4, WebM, and Ogg video formats, subject to the deployment's upload policy. Videos preview in their region and loop during playback.
Use a video that the target players can decode reliably, keep the file size appropriate for the available network, and check the first and last frames in the slide preview. If a video is unavailable during playback, review the playlist behavior for unavailable media and the player's connection.
### Template Backgrounds
Template backgrounds are separate from image-region content. A background can be a solid colour, an uploaded image, or a linear gradient. A background image belongs to the template, while an image region belongs to the slide content placed in that region.
### Media Library
The Media Library stores image and video files for reuse across slides, templates, and player content. Search by filename, filter by media type or usage, and sort by name, date, or file size. Results load in batches; use **Load more** to browse a larger library.
The image, video, and template background editors use the same media picker, so you can select an existing asset instead of uploading another copy. In the Media Library, use selection mode to choose multiple assets for deletion. Assets referenced by slides or templates are marked as in use and cannot be deleted.
### Uploads and Synchronization
Upload limits and allowed image or video types are controlled in [Administration settings](guide-admin.md#media-uploads). A file uploaded in one slide or template is referenced by that content; it is not automatically copied into other slides.
Players receive referenced media through the service synchronization process. A newly uploaded or changed file may need a short time to reach every player, especially when a player is offline. Check the player after synchronization before treating a missing file as a slide-design problem. Remove or replace media only after checking which templates or slides still reference it.
## Operations
### Background Updates
Pulse Signage performs routine work in the background so the web application does not need to wait for every refresh or cleanup operation. This includes refreshing data sources, synchronizing media and fonts, removing expired information, and keeping player state current.
Most background work happens automatically. If content appears stale, use the relevant feature page to check the source or player state first. A player that is offline cannot receive new media, fonts, slides, or commands until it reconnects.
When investigating stale content, check in this order:
1. Confirm the connected client is online and reporting the expected screen.
2. Confirm the screen points to the intended playlist.
3. Confirm the playlist contains the current slide in the expected order.
4. Check the source or asset used by the affected region.
5. Allow time for the player to refresh or synchronize after the change.
The task and system pages can help administrators investigate work that is delayed or failed.
### System Settings and Activity
System settings provide defaults and integrations used across the application. Depending on the deployment, they can include player behavior, announcement defaults, data-source refresh settings, email templates, and external service providers.
Activity history records important account and system changes. It is useful when you need to understand when a setting changed, investigate an unexpected update, or review recent administrative activity.
Change system-wide settings carefully because they can affect multiple screens, users, sources, or players. Use activity history to confirm what changed and when, especially after a display or synchronization problem begins.
+12 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "pulse-signage", "name": "pulse-signage",
"version": "2.10.6", "version": "2.13.3",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "pulse-signage", "name": "pulse-signage",
"version": "2.10.6", "version": "2.13.3",
"dependencies": { "dependencies": {
"@sparticuz/chromium": "^149.0.0", "@sparticuz/chromium": "^149.0.0",
"animate.css": "^4.1.1", "animate.css": "^4.1.1",
@@ -19,6 +19,7 @@
"jsqr": "^1.4.0", "jsqr": "^1.4.0",
"multer": "^2.2.0", "multer": "^2.2.0",
"mysql2": "^3.23.3", "mysql2": "^3.23.3",
"nodemailer": "^9.1.1",
"puppeteer-core": "^25.7.0", "puppeteer-core": "^25.7.0",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"ws": "^8.21.3" "ws": "^8.21.3"
@@ -1989,6 +1990,15 @@
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/nodemailer": {
"version": "9.1.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.1.1.tgz",
"integrity": "sha512-izw9mVKFix6YSnC9eLgV6g1opl9DUlRio9ZNcq+Wu9Ujn2UwF+8Nl0B8nz22kEC+CTZCvinkxwJ0DeFbb6NwcQ==",
"license": "MIT-0",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/nodemon": { "node_modules/nodemon": {
"version": "3.1.14", "version": "3.1.14",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz",
+2 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "pulse-signage", "name": "pulse-signage",
"version": "2.10.6", "version": "2.13.3",
"private": false, "private": false,
"description": "Pulse Signage application with MySQL and media storage", "description": "Pulse Signage application with MySQL and media storage",
"engines": { "engines": {
@@ -31,6 +31,7 @@
"jsqr": "^1.4.0", "jsqr": "^1.4.0",
"multer": "^2.2.0", "multer": "^2.2.0",
"mysql2": "^3.23.3", "mysql2": "^3.23.3",
"nodemailer": "^9.1.1",
"puppeteer-core": "^25.7.0", "puppeteer-core": "^25.7.0",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"ws": "^8.21.3" "ws": "^8.21.3"
+7 -2
View File
@@ -2,11 +2,15 @@
const crypto = require('crypto'); const crypto = require('crypto');
const PASSWORD_ITERATIONS = Number(process.env.PASSWORD_HASH_ITERATIONS || 310000); const PASSWORD_ITERATIONS = 310000;
const PASSWORD_KEY_LENGTH = 32; const PASSWORD_KEY_LENGTH = 32;
const PASSWORD_DIGEST = 'sha256'; const PASSWORD_DIGEST = 'sha256';
const SESSION_BYTES = 32; const SESSION_BYTES = 32;
function createOneTimeToken() {
return crypto.randomBytes(32).toString('hex');
}
function validatePasswordStrength(password, options) { function validatePasswordStrength(password, options) {
const value = String(password || ''); const value = String(password || '');
const requirements = options && options.policy const requirements = options && options.policy
@@ -91,5 +95,6 @@ module.exports = {
verifyPassword, verifyPassword,
validatePasswordStrength, validatePasswordStrength,
createSessionToken, createSessionToken,
hashSessionToken hashSessionToken,
createOneTimeToken
}; };
+54
View File
@@ -0,0 +1,54 @@
const DEFAULT_ACCOUNT_EMAIL_TEMPLATES = {
verificationSubject: 'Verify your Pulse Signage email address',
verificationBody: 'Hello [b][[display_name]][/b]!\n[[action_button]]\nThis [u]link[/u] expires in [i][[expiry_time]][/i].\nConfirm this email address: [[url]]',
resetSubject: 'Reset your Pulse Signage password',
resetBody: 'Hello [b][[display_name]][/b]!\n[[action_button]]\nThis [u]link[/u] expires in [i][[expiry_time]][/i].\nChoose a new password: [[url]]'
};
function formatAccountEmailExpiry(value, unit) {
const amount = Number(value);
const normalizedAmount = Number.isFinite(amount) && amount > 0 ? Math.round(amount) : 30;
const normalizedUnit = unit === 'hours' ? 'hour' : 'minute';
return normalizedAmount + ' ' + normalizedUnit + (normalizedAmount === 1 ? '' : 's');
}
function renderAccountEmailTemplate(subject, body, variables) {
const values = variables || {};
const replaceVariables = function (value) {
return String(value || '').replace(/\[\[([a-z_]+)\]\]/g, function (_match, key) {
return Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : _match;
});
};
const renderedSubject = replaceVariables(subject);
const renderedText = replaceVariables(body);
const plainText = renderedText.replace(/\[(?:b|i|u)\]([\s\S]*?)\[\/(?:b|i|u)\]/gi, '$1');
const escapedBody = renderedText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/\[b\]([\s\S]*?)\[\/b\]/gi, '<strong>$1</strong>').replace(/\[i\]([\s\S]*?)\[\/i\]/gi, '<em>$1</em>').replace(/\[u\]([\s\S]*?)\[\/u\]/gi, '<u>$1</u>');
const actionLabel = String(values.action_label || 'Continue').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const actionUrl = values.url ? String(values.url).replace(/&/g, '&amp;').replace(/"/g, '&quot;') : '';
const actionAlignment = values.action_alignment === 'left' || values.action_alignment === 'right' ? values.action_alignment : 'center';
const actionButton = actionUrl ? '<a href="' + actionUrl + '" style="display:inline-block;background:#111827;color:#ffffff;padding:12px 22px;text-decoration:none;border-radius:4px;font-weight:600;">' + actionLabel + '</a>' : '';
const actionBlock = actionButton ? '<div style="margin:24px 0;text-align:' + actionAlignment + ';">' + actionButton + '</div>' : '';
const plainLink = actionUrl ? '<a href="' + actionUrl + '">' + actionUrl + '</a>' : '';
const escapedBodyUrl = values.url ? String(values.url).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;') : '';
const hasButtonPlaceholder = escapedBody.indexOf('[[action_button]]') !== -1;
const hasUrlPlaceholder = String(body || '').indexOf('[[url]]') !== -1;
const bodyWithAction = hasButtonPlaceholder
? escapedBody.split(escapedBodyUrl).join(plainLink).replace(/\[\[action_button\]\]/g, actionBlock).replace(/\[\[action_link\]\]/g, plainLink)
: hasUrlPlaceholder
? escapedBody.split(actionUrl).join(actionBlock + plainLink)
: escapedBody.replace(/\[\[action_link\]\]/g, plainLink).replace(actionUrl, plainLink);
const bodyHtml = bodyWithAction.split(/\r?\n(?:[ \t]*\r?\n)+/).map(function (paragraph) {
const paragraphHtml = paragraph.replace(/\r?\n/g, '<br>');
if (paragraphHtml.indexOf(actionBlock) !== -1 && actionBlock) {
return paragraphHtml.split(actionBlock).map(function (part, index, parts) {
const text = part ? '<p style="margin:0 0 16px;">' + part + '</p>' : '';
return text + (index < parts.length - 1 ? actionBlock : '');
}).join('');
}
return paragraphHtml ? '<p style="margin:0 0 16px;">' + paragraphHtml + '</p>' : '';
}).join('');
const html = '<!doctype html><html><body style="margin:0;background:#f4f4f5;font-family:Arial,sans-serif;color:#27364b;"><div style="padding:24px 12px;"><div style="max-width:560px;margin:0 auto;text-align:center;color:#111827;font-size:20px;font-weight:700;padding:0 0 16px;">Pulse Signage</div><div style="max-width:560px;margin:0 auto;background:#ffffff;padding:32px;border-radius:4px;text-align:left;">' + bodyHtml + '</div></div></body></html>';
return { subject: renderedSubject, text: plainText, html: html };
}
module.exports = { DEFAULT_ACCOUNT_EMAIL_TEMPLATES, formatAccountEmailExpiry, renderAccountEmailTemplate };
+150 -23
View File
@@ -13,6 +13,7 @@ const TOKEN_URL_MAX_LENGTH = 1024;
const TOKEN_RESPONSE_PATH_MAX_LENGTH = 255; const TOKEN_RESPONSE_PATH_MAX_LENGTH = 255;
const TOKEN_HEADER_PREFIX_MAX_LENGTH = 64; const TOKEN_HEADER_PREFIX_MAX_LENGTH = 64;
const tokenCache = new Map(); const tokenCache = new Map();
const tokenRequests = new Map();
function normalizeUpdateIntervalUnit(value) { function normalizeUpdateIntervalUnit(value) {
const unit = String(value || '').trim().toLowerCase(); const unit = String(value || '').trim().toLowerCase();
@@ -59,7 +60,7 @@ function buildAuthHeaders(source) {
async function fetchApiSourcesData(pool) { async function fetchApiSourcesData(pool) {
const [apiSources] = await pool.query( const [apiSources] = await pool.query(
'SELECT id, name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_header_name, token_header_prefix, items_path, enabled, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM i_api_sources ORDER BY modified_at DESC, id DESC' 'SELECT id, name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_refresh_url, token_refresh_request_body_json, token_refresh_response_path, token_header_name, token_header_prefix, items_path, enabled, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM i_api_sources ORDER BY modified_at DESC, id DESC'
); );
return { apiSources: apiSources }; return { apiSources: apiSources };
@@ -67,7 +68,7 @@ async function fetchApiSourcesData(pool) {
async function fetchApiSourcesPage(pool, page, pageSize, searchTerm, sortKey, sortDirection) { async function fetchApiSourcesPage(pool, page, pageSize, searchTerm, sortKey, sortDirection) {
const paged = await fetchPagedRows(pool, { const paged = await fetchPagedRows(pool, {
selectSql: 'SELECT id, name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_header_name, token_header_prefix, items_path, enabled, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM i_api_sources ORDER BY modified_at DESC, id DESC', selectSql: 'SELECT id, name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_refresh_url, token_refresh_request_body_json, token_refresh_response_path, token_header_name, token_header_prefix, items_path, enabled, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM i_api_sources ORDER BY modified_at DESC, id DESC',
countSql: 'SELECT COUNT(*) AS count FROM i_api_sources', countSql: 'SELECT COUNT(*) AS count FROM i_api_sources',
searchColumns: ['name', 'api_url', 'last_pull_error'], searchColumns: ['name', 'api_url', 'last_pull_error'],
searchTerm: searchTerm, searchTerm: searchTerm,
@@ -91,7 +92,7 @@ async function fetchApiSourcesPage(pool, page, pageSize, searchTerm, sortKey, so
async function fetchApiSourceById(pool, id) { async function fetchApiSourceById(pool, id) {
const [rows] = await pool.query( const [rows] = await pool.query(
'SELECT id, name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_header_name, token_header_prefix, items_path, enabled, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM i_api_sources WHERE id = ?', 'SELECT id, name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_refresh_url, token_refresh_request_body_json, token_refresh_response_path, token_header_name, token_header_prefix, items_path, enabled, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_at, modified_at, created_by, modified_by FROM i_api_sources WHERE id = ?',
[id] [id]
); );
@@ -184,6 +185,9 @@ function getTokenCacheKey(source) {
source && (source.token_url || source.tokenUrl) || '', source && (source.token_url || source.tokenUrl) || '',
source && (source.token_request_body_json || source.tokenRequestBodyJson) || '', source && (source.token_request_body_json || source.tokenRequestBodyJson) || '',
source && (source.token_response_path || source.tokenResponsePath) || 'access_token', source && (source.token_response_path || source.tokenResponsePath) || 'access_token',
source && (source.token_refresh_url || source.tokenRefreshUrl) || '',
source && (source.token_refresh_request_body_json || source.tokenRefreshRequestBodyJson) || '',
source && (source.token_refresh_response_path || source.tokenRefreshResponsePath) || 'refresh_token',
source && (source.token_header_name || source.tokenHeaderName) || 'Authorization', source && (source.token_header_name || source.tokenHeaderName) || 'Authorization',
source && (source.token_header_prefix || source.tokenHeaderPrefix) || 'Bearer' source && (source.token_header_prefix || source.tokenHeaderPrefix) || 'Bearer'
]); ]);
@@ -193,11 +197,118 @@ function clearCachedToken(source) {
tokenCache.delete(getTokenCacheKey(source)); tokenCache.delete(getTokenCacheKey(source));
} }
async function fetchLoginToken(source) { function replaceRefreshToken(value, refreshToken) {
if (typeof value === 'string') {
return value.split('{{refresh_token}}').join(refreshToken);
}
if (Array.isArray(value)) {
return value.map(function (item) {
return replaceRefreshToken(item, refreshToken);
});
}
if (value && typeof value === 'object') {
return Object.keys(value).reduce(function (result, key) {
result[key] = replaceRefreshToken(value[key], refreshToken);
return result;
}, {});
}
return value;
}
function resolveTokenExpiry(parsed, token) {
const expiresIn = Number(parsed && (parsed.expires_in || parsed.expiresIn));
if (Number.isFinite(expiresIn) && expiresIn > 0) {
return { lifetimeMs: expiresIn * 1000 };
}
const explicitExpiry = parsed && (parsed.expires_at || parsed.expiresAt);
if (explicitExpiry !== undefined && explicitExpiry !== null) {
const expiryNumber = Number(explicitExpiry);
const expiryMs = Number.isFinite(expiryNumber)
? (expiryNumber < 100000000000 ? expiryNumber * 1000 : expiryNumber)
: Date.parse(String(explicitExpiry));
if (Number.isFinite(expiryMs) && expiryMs > Date.now()) {
return { expiresAt: expiryMs };
}
}
const tokenParts = String(token).split('.');
if (tokenParts.length === 3) {
try {
const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString('utf8'));
const expiryMs = Number(payload.exp) * 1000;
if (Number.isFinite(expiryMs) && expiryMs > Date.now()) {
return { expiresAt: expiryMs };
}
} catch (_error) {
// Opaque tokens do not contain a readable JWT expiry.
}
}
return { lifetimeMs: 300000 };
}
function cacheTokenResponse(source, parsed, previousRefreshToken) {
const tokenPath = source.token_response_path || source.tokenResponsePath || 'access_token';
const token = resolveResponsePath(parsed, tokenPath);
if (token === undefined || token === null || String(token).trim() === '') {
throw new Error('Token response did not contain a token at the configured path.');
}
const refreshPath = source.token_refresh_response_path || source.tokenRefreshResponsePath || 'refresh_token';
const responseRefreshToken = resolveResponsePath(parsed, refreshPath);
const refreshToken = responseRefreshToken === undefined || responseRefreshToken === null || String(responseRefreshToken).trim() === ''
? previousRefreshToken
: String(responseRefreshToken);
const expiry = resolveTokenExpiry(parsed, token);
const expiresAt = expiry.expiresAt || Date.now() + Math.max(1000, expiry.lifetimeMs - Math.min(60000, expiry.lifetimeMs * 0.1));
const record = { value: String(token), refreshToken: refreshToken, expiresAt: expiresAt };
tokenCache.set(getTokenCacheKey(source), record);
return record;
}
async function parseTokenResponse(response, source, previousRefreshToken) {
if (!response.ok) {
return null;
}
let parsed;
try {
parsed = JSON.parse(String(response.bodyText || '').trim());
} catch (_error) {
throw new Error('Token response was not valid JSON.');
}
return cacheTokenResponse(source, parsed, previousRefreshToken);
}
async function refreshLoginToken(source, cached) {
const refreshUrl = source.token_refresh_url || source.tokenRefreshUrl || source.token_url || source.tokenUrl;
if (!cached || !cached.refreshToken) {
return null;
}
const configuredBody = parseJsonRequestBody(source.token_refresh_request_body_json || source.tokenRefreshRequestBodyJson, 'Refresh request body');
const refreshBody = configuredBody === undefined
? { grant_type: 'refresh_token', refresh_token: cached.refreshToken }
: replaceRefreshToken(configuredBody, cached.refreshToken);
const response = await loadUrlText(refreshUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(refreshBody)
});
return parseTokenResponse(response, source, cached.refreshToken);
}
async function fetchLoginTokenUncached(source) {
const cacheKey = getTokenCacheKey(source); const cacheKey = getTokenCacheKey(source);
const cached = tokenCache.get(cacheKey); const cached = tokenCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) { if (cached && cached.expiresAt > Date.now()) {
return cached.value; return cached;
}
if (cached && cached.refreshToken) {
const refreshed = await refreshLoginToken(source, cached);
if (refreshed) {
return refreshed;
}
} }
const tokenUrl = source.token_url || source.tokenUrl; const tokenUrl = source.token_url || source.tokenUrl;
@@ -208,29 +319,25 @@ async function fetchLoginToken(source) {
headers: tokenHeaders, headers: tokenHeaders,
body: tokenBody === undefined ? undefined : JSON.stringify(tokenBody) body: tokenBody === undefined ? undefined : JSON.stringify(tokenBody)
}); });
if (!response.ok) { const record = await parseTokenResponse(response, source, cached && cached.refreshToken);
if (!record) {
throw new Error(`Unable to obtain API token (${response.statusCode}).`); throw new Error(`Unable to obtain API token (${response.statusCode}).`);
} }
return record;
}
let parsed; async function fetchLoginToken(source) {
try { const cacheKey = getTokenCacheKey(source);
parsed = JSON.parse(String(response.bodyText || '').trim()); const cached = tokenCache.get(cacheKey);
} catch (_error) { if (cached && cached.expiresAt > Date.now()) {
throw new Error('Token response was not valid JSON.'); return cached.value;
} }
if (!tokenRequests.has(cacheKey)) {
const tokenPath = source.token_response_path || source.tokenResponsePath || 'access_token'; tokenRequests.set(cacheKey, fetchLoginTokenUncached(source).finally(function () {
const token = resolveResponsePath(parsed, tokenPath); tokenRequests.delete(cacheKey);
if (token === undefined || token === null || String(token).trim() === '') { }));
throw new Error('Token response did not contain a token at the configured path.');
} }
return (await tokenRequests.get(cacheKey)).value;
const expiresIn = Number(parsed && (parsed.expires_in || parsed.expiresIn));
const lifetimeMs = Number.isFinite(expiresIn) && expiresIn > 0
? Math.max(30000, expiresIn * 1000 - 60000)
: 300000;
tokenCache.set(cacheKey, { value: String(token), expiresAt: Date.now() + lifetimeMs });
return String(token);
} }
async function buildRequestHeaders(source) { async function buildRequestHeaders(source) {
@@ -310,6 +417,9 @@ function buildApiSourcePayload(req, existingApiSource) {
const tokenUrl = validateMaxLength(readBodyValue('token_url', readBodyValue('tokenUrl', fallback.token_url || '')) || '', TOKEN_URL_MAX_LENGTH, 'API token URL'); const tokenUrl = validateMaxLength(readBodyValue('token_url', readBodyValue('tokenUrl', fallback.token_url || '')) || '', TOKEN_URL_MAX_LENGTH, 'API token URL');
const tokenRequestBodyJson = validateMaxLength(readBodyValue('token_request_body_json', readBodyValue('tokenRequestBodyJson', fallback.token_request_body_json || '')) || '', REQUEST_BODY_MAX_LENGTH, 'Login request body'); const tokenRequestBodyJson = validateMaxLength(readBodyValue('token_request_body_json', readBodyValue('tokenRequestBodyJson', fallback.token_request_body_json || '')) || '', REQUEST_BODY_MAX_LENGTH, 'Login request body');
const tokenResponsePath = validateMaxLength(readBodyValue('token_response_path', readBodyValue('tokenResponsePath', fallback.token_response_path || 'access_token')) || 'access_token', TOKEN_RESPONSE_PATH_MAX_LENGTH, 'Token response path'); const tokenResponsePath = validateMaxLength(readBodyValue('token_response_path', readBodyValue('tokenResponsePath', fallback.token_response_path || 'access_token')) || 'access_token', TOKEN_RESPONSE_PATH_MAX_LENGTH, 'Token response path');
const tokenRefreshUrl = validateMaxLength(readBodyValue('token_refresh_url', readBodyValue('tokenRefreshUrl', fallback.token_refresh_url || '')) || '', TOKEN_URL_MAX_LENGTH, 'API refresh URL');
const tokenRefreshRequestBodyJson = validateMaxLength(readBodyValue('token_refresh_request_body_json', readBodyValue('tokenRefreshRequestBodyJson', fallback.token_refresh_request_body_json || '')) || '', REQUEST_BODY_MAX_LENGTH, 'Refresh request body');
const tokenRefreshResponsePath = validateMaxLength(readBodyValue('token_refresh_response_path', readBodyValue('tokenRefreshResponsePath', fallback.token_refresh_response_path || 'refresh_token')) || 'refresh_token', TOKEN_RESPONSE_PATH_MAX_LENGTH, 'Refresh token response path');
const tokenHeaderName = validateMaxLength(readBodyValue('token_header_name', readBodyValue('tokenHeaderName', fallback.token_header_name || 'Authorization')) || 'Authorization', AUTH_MAX_LENGTH, 'Token header name'); const tokenHeaderName = validateMaxLength(readBodyValue('token_header_name', readBodyValue('tokenHeaderName', fallback.token_header_name || 'Authorization')) || 'Authorization', AUTH_MAX_LENGTH, 'Token header name');
const tokenHeaderPrefix = validateMaxLength(readBodyValue('token_header_prefix', readBodyValue('tokenHeaderPrefix', fallback.token_header_prefix || 'Bearer')) || '', TOKEN_HEADER_PREFIX_MAX_LENGTH, 'Token prefix'); const tokenHeaderPrefix = validateMaxLength(readBodyValue('token_header_prefix', readBodyValue('tokenHeaderPrefix', fallback.token_header_prefix || 'Bearer')) || '', TOKEN_HEADER_PREFIX_MAX_LENGTH, 'Token prefix');
const itemsPath = validateMaxLength(readBodyValue('items_path', readBodyValue('itemsPath', fallback.items_path || '')) || '', ITEMS_PATH_MAX_LENGTH, 'API source items path'); const itemsPath = validateMaxLength(readBodyValue('items_path', readBodyValue('itemsPath', fallback.items_path || '')) || '', ITEMS_PATH_MAX_LENGTH, 'API source items path');
@@ -369,6 +479,7 @@ function buildApiSourcePayload(req, existingApiSource) {
parseJsonRequestBody(requestBodyJson, 'API request body'); parseJsonRequestBody(requestBodyJson, 'API request body');
parseJsonRequestBody(tokenRequestBodyJson, 'Login request body'); parseJsonRequestBody(tokenRequestBodyJson, 'Login request body');
parseJsonRequestBody(tokenRefreshRequestBodyJson, 'Refresh request body');
if (authMethod === 'token_login') { if (authMethod === 'token_login') {
if (!tokenUrl) { if (!tokenUrl) {
@@ -393,6 +504,19 @@ function buildApiSourcePayload(req, existingApiSource) {
} }
} }
if (tokenRefreshUrl) {
try {
const refreshParsedUrl = new URL(tokenRefreshUrl);
if (refreshParsedUrl.protocol !== 'http:' && refreshParsedUrl.protocol !== 'https:') {
throw new Error('invalid protocol');
}
} catch (_error) {
const error = new Error('Enter a valid API refresh URL.');
error.statusCode = 400;
throw error;
}
}
return { return {
name: name, name: name,
apiUrl: parsedUrl.toString(), apiUrl: parsedUrl.toString(),
@@ -407,6 +531,9 @@ function buildApiSourcePayload(req, existingApiSource) {
tokenUrl: tokenUrl, tokenUrl: tokenUrl,
tokenRequestBodyJson: tokenRequestBodyJson, tokenRequestBodyJson: tokenRequestBodyJson,
tokenResponsePath: tokenResponsePath, tokenResponsePath: tokenResponsePath,
tokenRefreshUrl: tokenRefreshUrl,
tokenRefreshRequestBodyJson: tokenRefreshRequestBodyJson,
tokenRefreshResponsePath: tokenRefreshResponsePath,
tokenHeaderName: tokenHeaderName, tokenHeaderName: tokenHeaderName,
tokenHeaderPrefix: tokenHeaderPrefix, tokenHeaderPrefix: tokenHeaderPrefix,
itemsPath: itemsPath, itemsPath: itemsPath,
+25
View File
@@ -21,8 +21,33 @@ const SETTING_DEFINITIONS = [
{ key: 'security.login_max_attempts', type: 'integer', min: 1, defaultValue: 5 }, { key: 'security.login_max_attempts', type: 'integer', min: 1, defaultValue: 5 },
{ key: 'security.login_lockout_minutes', type: 'integer', min: 1, defaultValue: 15 }, { key: 'security.login_lockout_minutes', type: 'integer', min: 1, defaultValue: 15 },
{ key: 'security.login_rate_limit_scope', type: 'enum', values: ['both', 'username', 'ip'], defaultValue: 'both' }, { key: 'security.login_rate_limit_scope', type: 'enum', values: ['both', 'username', 'ip'], defaultValue: 'both' },
{ key: 'security.allow_admin_email_verification_bypass', type: 'boolean', defaultValue: true },
{ key: 'email.smtp_enabled', type: 'boolean', defaultValue: false },
{ key: 'email.smtp_host', type: 'string', defaultValue: '' },
{ key: 'email.smtp_port', type: 'integer', min: 1, defaultValue: 587 },
{ key: 'email.smtp_security', type: 'enum', values: ['none', 'starttls', 'tls'], defaultValue: 'starttls' },
{ key: 'email.smtp_username', type: 'string', defaultValue: '' },
{ key: 'email.smtp_password', type: 'string', defaultValue: '' },
{ key: 'email.from_address', type: 'string', defaultValue: '' },
{ key: 'email.from_name', type: 'string', defaultValue: 'Pulse Signage' },
{ key: 'email.verification_expiry_minutes', type: 'integer', min: 1, defaultValue: 30 },
{ key: 'email.reset_expiry_minutes', type: 'integer', min: 1, defaultValue: 30 },
{ key: 'email.invitation_expiry_hours', type: 'integer', min: 1, defaultValue: 24 },
{ key: 'email.verification_subject', type: 'string', defaultValue: 'Verify your Pulse Signage email address' },
{ key: 'email.verification_body', type: 'string', defaultValue: 'Hello [b][[display_name]][/b]!\n[[action_button]]\nThis [u]link[/u] expires in [i][[expiry_time]][/i].\nConfirm this email address: [[url]]' },
{ key: 'email.reset_subject', type: 'string', defaultValue: 'Reset your Pulse Signage password' },
{ key: 'email.reset_body', type: 'string', defaultValue: 'Hello [b][[display_name]][/b]!\n[[action_button]]\nThis [u]link[/u] expires in [i][[expiry_time]][/i].\nChoose a new password: [[url]]' },
{ key: 'email.verification_button_alignment', type: 'enum', values: ['left', 'center', 'right'], defaultValue: 'center' },
{ key: 'email.verification_button_text', type: 'string', defaultValue: 'Verify email address' },
{ key: 'email.reset_button_alignment', type: 'enum', values: ['left', 'center', 'right'], defaultValue: 'center' },
{ key: 'email.reset_button_text', type: 'string', defaultValue: 'Reset password' },
{ key: 'email.invitation_subject', type: 'string', defaultValue: 'You have been invited to Pulse Signage' },
{ key: 'email.invitation_body', type: 'string', defaultValue: 'Hello [b][[display_name]][/b]!\n[[action_button]]\nThis [u]invitation link[/u] expires in [i][[expiry_time]][/i].\nCreate your account: [[url]]' },
{ key: 'email.invitation_button_alignment', type: 'enum', values: ['left', 'center', 'right'], defaultValue: 'center' },
{ key: 'email.invitation_button_text', type: 'string', defaultValue: 'Accept invitation' },
{ key: 'audit.enabled', type: 'boolean', defaultValue: true }, { key: 'audit.enabled', type: 'boolean', defaultValue: true },
{ key: 'audit.categories', type: 'string_array', defaultValue: ['authentication', 'security', 'sessions', 'users', 'roles', 'system-settings'] }, { key: 'audit.categories', type: 'string_array', defaultValue: ['authentication', 'security', 'sessions', 'users', 'roles', 'system-settings'] },
{ key: 'audit.screen_control_commands', type: 'string_array', defaultValue: [] },
{ key: 'audit.include_request_metadata', type: 'boolean', defaultValue: true }, { key: 'audit.include_request_metadata', type: 'boolean', defaultValue: true },
{ key: 'audit.retention_days', type: 'integer', min: 0, defaultValue: 180 }, { key: 'audit.retention_days', type: 'integer', min: 0, defaultValue: 180 },
{ key: 'uploads.image_max_bytes', type: 'integer', min: 1, defaultValue: 100 * 1024 * 1024 }, { key: 'uploads.image_max_bytes', type: 'integer', min: 1, defaultValue: 100 * 1024 * 1024 },
+47 -2
View File
@@ -15,7 +15,9 @@ const AUDIT_EVENT_CATEGORIES = Object.freeze({
CANVAS_SIZES: 'canvas-sizes', CANVAS_SIZES: 'canvas-sizes',
API_SOURCES: 'api-sources', API_SOURCES: 'api-sources',
RSS_FEEDS: 'rss-feeds', RSS_FEEDS: 'rss-feeds',
TIMETABLES: 'timetables' TIMETABLES: 'timetables',
WEATHER: 'weather',
SCREEN_CONTROLS: 'screen-controls'
}); });
const AUDIT_CATEGORY_KEYS = Object.freeze(Object.values(AUDIT_EVENT_CATEGORIES)); const AUDIT_CATEGORY_KEYS = Object.freeze(Object.values(AUDIT_EVENT_CATEGORIES));
const AUDIT_CATEGORY_LABELS = Object.freeze({ const AUDIT_CATEGORY_LABELS = Object.freeze({
@@ -33,10 +35,42 @@ const AUDIT_CATEGORY_LABELS = Object.freeze({
'canvas-sizes': 'Canvas Sizes', 'canvas-sizes': 'Canvas Sizes',
'api-sources': 'API Sources', 'api-sources': 'API Sources',
'rss-feeds': 'RSS Feeds', 'rss-feeds': 'RSS Feeds',
timetables: 'Timetables' timetables: 'Timetables',
weather: 'Weather',
'screen-controls': 'Screen Controls'
});
const SCREEN_CONTROL_COMMAND_KEYS = Object.freeze(['pause', 'blackout', 'reload', 'navigation', 'moveclient', 'setclientname']);
const SCREEN_CONTROL_COMMAND_LABELS = Object.freeze({
pause: 'Pause / Resume',
blackout: 'Blackout / Restore',
reload: 'Reload',
navigation: 'Forward / Back',
moveclient: 'Move client',
setclientname: 'Rename client'
}); });
const { fetchAppSettings } = require('./app-settings'); const { fetchAppSettings } = require('./app-settings');
function formatUserAgentLabel(userAgent) {
const value = String(userAgent || '').trim();
if (!value) return '';
const browserMatch = value.match(/(?:Edg|OPR|Chrome|Firefox|Version|Electron)\/([\d.]+)/i);
let browser = '';
if (/Edg\//i.test(value)) browser = 'Edge';
else if (/OPR\//i.test(value)) browser = 'Opera';
else if (/Electron\//i.test(value)) browser = 'Electron';
else if (/Chrome\//i.test(value)) browser = 'Chrome';
else if (/Firefox\//i.test(value)) browser = 'Firefox';
else if (/Version\/.*Safari\//i.test(value)) browser = 'Safari';
const browserLabel = browserMatch && browser ? browser + ' ' + browserMatch[1] : browser;
let operatingSystem = '';
if (/Windows NT/i.test(value)) operatingSystem = 'Windows';
else if (/Macintosh|Mac OS X/i.test(value)) operatingSystem = 'macOS';
else if (/Android/i.test(value)) operatingSystem = 'Android';
else if (/iPhone|iPad|iPod/i.test(value)) operatingSystem = 'iOS';
else if (/Linux/i.test(value)) operatingSystem = 'Linux';
return [browserLabel, operatingSystem].filter(Boolean).join(' on ') || value;
}
function normalizeDetails(details) { function normalizeDetails(details) {
if (details === undefined || details === null) { if (details === undefined || details === null) {
return null; return null;
@@ -101,6 +135,14 @@ async function recordRequestAuditEvent(pool, req, event) {
if (!settings['audit.enabled'] || !enabledCategories.includes(category)) { if (!settings['audit.enabled'] || !enabledCategories.includes(category)) {
return; return;
} }
if (category === 'screen-controls') {
const command = String(event && event.eventType || '').replace(/^screen-control\./, '').trim().toLowerCase();
const commandGroup = command === 'previous' || command === 'next' ? 'navigation' : command;
const enabledCommands = Array.isArray(settings['audit.screen_control_commands']) ? settings['audit.screen_control_commands'] : [];
if (!enabledCommands.includes(commandGroup)) {
return;
}
}
const metadata = settings['audit.include_request_metadata'] ? getRequestMetadata(req) : {}; const metadata = settings['audit.include_request_metadata'] ? getRequestMetadata(req) : {};
await recordAuditEvent(pool, Object.assign({}, event, metadata)); await recordAuditEvent(pool, Object.assign({}, event, metadata));
} catch (error) { } catch (error) {
@@ -113,6 +155,9 @@ module.exports = {
AUDIT_EVENT_CATEGORIES, AUDIT_EVENT_CATEGORIES,
AUDIT_CATEGORY_KEYS, AUDIT_CATEGORY_KEYS,
AUDIT_CATEGORY_LABELS, AUDIT_CATEGORY_LABELS,
SCREEN_CONTROL_COMMAND_KEYS,
SCREEN_CONTROL_COMMAND_LABELS,
formatUserAgentLabel,
getRequestMetadata, getRequestMetadata,
buildAuditChanges, buildAuditChanges,
recordAuditEvent, recordAuditEvent,
+43
View File
@@ -0,0 +1,43 @@
// SMTP delivery for account notifications.
const nodemailer = require('nodemailer');
function getSmtpConfig(settings) {
return {
enabled: Boolean(settings['email.smtp_enabled']),
host: String(settings['email.smtp_host'] || '').trim(),
port: Number(settings['email.smtp_port']) || 587,
security: String(settings['email.smtp_security'] || 'starttls'),
username: String(settings['email.smtp_username'] || '').trim(),
password: String(settings['email.smtp_password'] || ''),
fromAddress: String(settings['email.from_address'] || '').trim(),
fromName: String(settings['email.from_name'] || '').trim()
};
}
function createMailTransport(settings) {
const config = getSmtpConfig(settings);
if (!config.enabled || !config.host || !config.fromAddress) {
return null;
}
return nodemailer.createTransport({
host: config.host,
port: config.port,
secure: config.security === 'tls',
requireTLS: config.security === 'starttls',
auth: config.username ? { user: config.username, pass: config.password } : undefined
});
}
async function sendAccountEmail(settings, message) {
const transport = createMailTransport(settings);
if (!transport) {
throw new Error('Email delivery is not configured.');
}
const config = getSmtpConfig(settings);
return transport.sendMail(Object.assign({}, message, {
from: config.fromName ? '"' + config.fromName.replace(/"/g, '') + '" <' + config.fromAddress + '>' : config.fromAddress,
}));
}
module.exports = { getSmtpConfig, createMailTransport, sendAccountEmail };
+17 -2
View File
@@ -101,7 +101,22 @@ function stripEditorOnlyMarkup(value) {
} }
function normalizeEditorMarkup(value) { function normalizeEditorMarkup(value) {
return String(value === undefined || value === null ? '' : value).trim(); return String(value === undefined || value === null ? '' : value)
.replace(/https?:\/\/[^"'\s<>]+(\/media\/[^"'\s<>)]*)/gi, '$1')
.trim();
}
function normalizeEditorMediaReferences(value) {
if (Array.isArray(value)) {
return value.map(normalizeEditorMediaReferences);
}
if (value && typeof value === 'object') {
Object.keys(value).forEach((key) => {
value[key] = normalizeEditorMediaReferences(value[key]);
});
return value;
}
return typeof value === 'string' ? normalizeEditorMarkup(value) : value;
} }
async function fetchSlideById(pool, id) { async function fetchSlideById(pool, id) {
@@ -507,7 +522,7 @@ async function buildTemplateContent(pool, template, body, filesByField, existing
}; };
} }
} }
return content; return normalizeEditorMediaReferences(content);
} }
async function buildSlidePayload(pool, req, existingSlide) { async function buildSlidePayload(pool, req, existingSlide) {
+59
View File
@@ -103,6 +103,24 @@ async function ensureSchema(pool, options) {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`); `);
await pool.query(`
CREATE TABLE IF NOT EXISTS c_media_assets (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
media_path VARCHAR(512) NOT NULL UNIQUE,
original_name VARCHAR(255) NOT NULL,
media_type VARCHAR(16) NOT NULL,
mime_type VARCHAR(128) NOT NULL,
file_size BIGINT UNSIGNED NOT NULL DEFAULT 0,
is_published TINYINT(1) NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by INT NULL,
modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
modified_by INT NULL,
INDEX idx_c_media_assets_type (media_type),
INDEX idx_c_media_assets_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
await pool.query(` await pool.query(`
CREATE TABLE IF NOT EXISTS c_playlist_slides ( CREATE TABLE IF NOT EXISTS c_playlist_slides (
id INT AUTO_INCREMENT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
@@ -249,6 +267,9 @@ async function ensureSchema(pool, options) {
token_url VARCHAR(1024) NULL, token_url VARCHAR(1024) NULL,
token_request_body_json MEDIUMTEXT NULL, token_request_body_json MEDIUMTEXT NULL,
token_response_path VARCHAR(255) NULL DEFAULT 'access_token', token_response_path VARCHAR(255) NULL DEFAULT 'access_token',
token_refresh_url VARCHAR(1024) NULL,
token_refresh_request_body_json MEDIUMTEXT NULL,
token_refresh_response_path VARCHAR(255) NULL DEFAULT 'refresh_token',
token_header_name VARCHAR(255) NULL DEFAULT 'Authorization', token_header_name VARCHAR(255) NULL DEFAULT 'Authorization',
token_header_prefix VARCHAR(64) NULL DEFAULT 'Bearer', token_header_prefix VARCHAR(64) NULL DEFAULT 'Bearer',
items_path VARCHAR(255) NULL, items_path VARCHAR(255) NULL,
@@ -343,11 +364,18 @@ async function ensureSchema(pool, options) {
id INT AUTO_INCREMENT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NULL, name VARCHAR(255) NULL,
username VARCHAR(255) NOT NULL UNIQUE, username VARCHAR(255) NOT NULL UNIQUE,
email VARCHAR(320) NULL,
email_verified_at DATETIME NULL,
pending_email VARCHAR(320) NULL,
pending_email_token_hash CHAR(64) NULL,
pending_email_expires_at DATETIME NULL,
password_hash CHAR(64) NOT NULL, password_hash CHAR(64) NOT NULL,
password_salt VARCHAR(64) NOT NULL, password_salt VARCHAR(64) NOT NULL,
password_iterations INT NOT NULL, password_iterations INT NOT NULL,
must_change_password TINYINT(1) NOT NULL DEFAULT 0, must_change_password TINYINT(1) NOT NULL DEFAULT 0,
account_locked TINYINT(1) NOT NULL DEFAULT 0, account_locked TINYINT(1) NOT NULL DEFAULT 0,
last_login_at DATETIME NULL,
last_login_ip VARCHAR(255) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by INT NULL, created_by INT NULL,
modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
@@ -355,6 +383,37 @@ async function ensureSchema(pool, options) {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`); `);
await pool.query(`
CREATE TABLE IF NOT EXISTS a_account_tokens (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
token_type VARCHAR(32) NOT NULL,
token_hash CHAR(64) NOT NULL UNIQUE,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_account_tokens_user FOREIGN KEY (user_id) REFERENCES a_users(id) ON DELETE CASCADE,
INDEX idx_account_tokens_lookup (token_type, token_hash, expires_at),
INDEX idx_account_tokens_user_type (user_id, token_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS a_user_invitations (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(320) NOT NULL,
name VARCHAR(255) NULL,
role_ids_json TEXT NOT NULL,
token_hash CHAR(64) NOT NULL UNIQUE,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by INT NULL,
INDEX idx_user_invitations_email (email, used_at, expires_at),
INDEX idx_user_invitations_created_by (created_by, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
await pool.query(` await pool.query(`
CREATE TABLE IF NOT EXISTS a_roles ( CREATE TABLE IF NOT EXISTS a_roles (
id INT AUTO_INCREMENT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
+92 -1
View File
@@ -504,7 +504,10 @@ const VERSIONED_MIGRATIONS = [
await ensureColumn(pool, 'i_api_sources', 'token_url', 'VARCHAR(1024) NULL', 'auth_header_value'); await ensureColumn(pool, 'i_api_sources', 'token_url', 'VARCHAR(1024) NULL', 'auth_header_value');
await ensureColumn(pool, 'i_api_sources', 'token_request_body_json', 'MEDIUMTEXT NULL', 'token_url'); await ensureColumn(pool, 'i_api_sources', 'token_request_body_json', 'MEDIUMTEXT NULL', 'token_url');
await ensureColumn(pool, 'i_api_sources', 'token_response_path', "VARCHAR(255) NULL DEFAULT 'access_token'", 'token_request_body_json'); await ensureColumn(pool, 'i_api_sources', 'token_response_path', "VARCHAR(255) NULL DEFAULT 'access_token'", 'token_request_body_json');
await ensureColumn(pool, 'i_api_sources', 'token_header_name', "VARCHAR(255) NULL DEFAULT 'Authorization'", 'token_response_path'); await ensureColumn(pool, 'i_api_sources', 'token_refresh_url', 'VARCHAR(1024) NULL', 'token_response_path');
await ensureColumn(pool, 'i_api_sources', 'token_refresh_request_body_json', 'MEDIUMTEXT NULL', 'token_refresh_url');
await ensureColumn(pool, 'i_api_sources', 'token_refresh_response_path', "VARCHAR(255) NULL DEFAULT 'refresh_token'", 'token_refresh_request_body_json');
await ensureColumn(pool, 'i_api_sources', 'token_header_name', "VARCHAR(255) NULL DEFAULT 'Authorization'", 'token_refresh_response_path');
await ensureColumn(pool, 'i_api_sources', 'token_header_prefix', "VARCHAR(64) NULL DEFAULT 'Bearer'", 'token_header_name'); await ensureColumn(pool, 'i_api_sources', 'token_header_prefix', "VARCHAR(64) NULL DEFAULT 'Bearer'", 'token_header_name');
} }
}, },
@@ -561,6 +564,94 @@ const VERSIONED_MIGRATIONS = [
run: async function (pool) { run: async function (pool) {
await ensureColumn(pool, 'd_onboarding_devices', 'last_seen_at', 'TIMESTAMP NULL', 'screen_id'); await ensureColumn(pool, 'd_onboarding_devices', 'last_seen_at', 'TIMESTAMP NULL', 'screen_id');
} }
},
{
version: '2.10.7',
label: 'v2.10.7 API token refresh settings schema',
run: async function (pool) {
await ensureColumn(pool, 'i_api_sources', 'token_refresh_url', 'VARCHAR(1024) NULL', 'token_response_path');
await ensureColumn(pool, 'i_api_sources', 'token_refresh_request_body_json', 'MEDIUMTEXT NULL', 'token_refresh_url');
await ensureColumn(pool, 'i_api_sources', 'token_refresh_response_path', "VARCHAR(255) NULL DEFAULT 'refresh_token'", 'token_refresh_request_body_json');
}
},
{
version: '2.11.0',
label: 'v2.11.0 account email and password reset schema',
run: async function (pool) {
await ensureColumn(pool, 'a_users', 'email', 'VARCHAR(320) NULL', 'username');
await ensureColumn(pool, 'a_users', 'email_verified_at', 'DATETIME NULL', 'email');
await ensureColumn(pool, 'a_users', 'pending_email', 'VARCHAR(320) NULL', 'email_verified_at');
await ensureColumn(pool, 'a_users', 'pending_email_token_hash', 'CHAR(64) NULL', 'pending_email');
await ensureColumn(pool, 'a_users', 'pending_email_expires_at', 'DATETIME NULL', 'pending_email_token_hash');
await ensureColumn(pool, 'a_users', 'last_login_at', 'DATETIME NULL', 'modified_by');
await ensureColumn(pool, 'a_users', 'last_login_ip', 'VARCHAR(255) NULL', 'last_login_at');
await pool.query(`
CREATE TABLE IF NOT EXISTS a_account_tokens (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
token_type VARCHAR(32) NOT NULL,
token_hash CHAR(64) NOT NULL UNIQUE,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_account_tokens_user FOREIGN KEY (user_id) REFERENCES a_users(id) ON DELETE CASCADE,
INDEX idx_account_tokens_lookup (token_type, token_hash, expires_at),
INDEX idx_account_tokens_user_type (user_id, token_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
}
},
{
version: '2.11.1',
label: 'v2.11.1 user invitations schema',
run: async function (pool) {
await pool.query(`
CREATE TABLE IF NOT EXISTS a_user_invitations (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(320) NOT NULL,
name VARCHAR(255) NULL,
role_ids_json TEXT NOT NULL,
token_hash CHAR(64) NOT NULL UNIQUE,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by INT NULL,
INDEX idx_user_invitations_email (email, used_at, expires_at),
INDEX idx_user_invitations_created_by (created_by, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
}
},
{
version: '2.13.0',
label: 'v2.13.0 media library schema',
run: async function (pool) {
await pool.query(`
CREATE TABLE IF NOT EXISTS c_media_assets (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
media_path VARCHAR(512) NOT NULL UNIQUE,
original_name VARCHAR(255) NOT NULL,
media_type VARCHAR(16) NOT NULL,
mime_type VARCHAR(128) NOT NULL,
file_size BIGINT UNSIGNED NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by INT NULL,
modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
modified_by INT NULL,
INDEX idx_c_media_assets_type (media_type),
INDEX idx_c_media_assets_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
}
},
{
version: '2.13.1',
label: 'v2.13.1 pending media upload visibility',
run: async function (pool) {
if (!(await columnExists(pool, 'c_media_assets', 'is_published'))) {
await pool.query('ALTER TABLE c_media_assets ADD COLUMN is_published TINYINT(1) NOT NULL DEFAULT 1 AFTER file_size');
}
}
} }
]; ];
+55
View File
@@ -13,6 +13,7 @@ const { createPlayerPlaylistService } = require('../player/playlist');
const { commitDeviceBinding, bindPlayerToScreen, getOnboardingStatus, getPlayerPublicBaseUrl } = require('../player/onboarding'); const { commitDeviceBinding, bindPlayerToScreen, getOnboardingStatus, getPlayerPublicBaseUrl } = require('../player/onboarding');
const { createStyledQrCodeSvg } = require('../data/qr-code'); const { createStyledQrCodeSvg } = require('../data/qr-code');
const { verifyPageAuthToken } = require('#src/request-auth'); const { verifyPageAuthToken } = require('#src/request-auth');
const { collectLocalControlUsers } = require('../web/lib/local-control-users');
function createThinClientConfig() { function createThinClientConfig() {
@@ -186,6 +187,7 @@ async function start() {
const server = http.createServer(app); const server = http.createServer(app);
const pool = common.createPool(); const pool = common.createPool();
const config = createThinClientConfig(); const config = createThinClientConfig();
const localPlayerInternalUrl = String(process.env.LOCAL_PLAYER_INTERNAL_URL || process.env.PLAYER_INTERNAL_URL || '').trim().replace(/\/$/, '');
const playerPlaylistService = createPlayerPlaylistService({ const playerPlaylistService = createPlayerPlaylistService({
pool: pool, pool: pool,
common: common, common: common,
@@ -416,6 +418,18 @@ async function start() {
return sendPlayerCommandToSocket(socket, commandPayload); return sendPlayerCommandToSocket(socket, commandPayload);
} }
async function syncLocalControlOnRegistration(socket, player) {
const playerInternalUrl = String(player && player.internal_base_url || '').trim().replace(/\/$/, '');
if (localPlayerInternalUrl && playerInternalUrl === localPlayerInternalUrl) {
return;
}
const users = await collectLocalControlUsers(pool);
await sendPlayerCommandToSocket(socket, {
command: 'sync-local-control',
users: users
});
}
function sendPlayerCommandToSocket(socket, commandPayload) { function sendPlayerCommandToSocket(socket, commandPayload) {
if (!socket || socket.readyState !== WebSocket.OPEN) { if (!socket || socket.readyState !== WebSocket.OPEN) {
return Promise.resolve({ ok: false, status: 503, error: 'Player is not connected.' }); return Promise.resolve({ ok: false, status: 503, error: 'Player is not connected.' });
@@ -1009,6 +1023,9 @@ async function start() {
} }
logBridge(`Player ${formatPlayerConnectionLabel(deviceId)} has connected`); logBridge(`Player ${formatPlayerConnectionLabel(deviceId)} has connected`);
socket.send(JSON.stringify({ type: 'registered', ok: true, player: player })); socket.send(JSON.stringify({ type: 'registered', ok: true, player: player }));
syncLocalControlOnRegistration(socket, player).catch(function (error) {
logBridge(`Unable to synchronize Local Control authorization for ${formatPlayerConnectionLabel(deviceId)}`, error);
});
return; return;
} }
@@ -1327,6 +1344,44 @@ async function start() {
} }
}); });
app.post('/api/internal/sync/player-control', requireRequestAuth, async function (_req, res, next) {
try {
logBridge('Relaying player control sync request to web');
const webBaseUrl = resolveWebBaseUrl(_req);
if (!webBaseUrl) {
return res.status(502).json({ error: 'Web base URL is not configured.' });
}
const requestBody = _req.body && typeof _req.body === 'object' && !Array.isArray(_req.body)
? Object.assign({}, _req.body)
: {};
const response = await fetch(`${webBaseUrl}/api/internal/sync/player-control`, {
method: 'POST',
headers: Object.assign({
Accept: 'application/json',
'Content-Type': 'application/json'
}, createRequestAuthHeaders({
method: 'POST',
pathname: '/api/internal/sync/player-control',
body: requestBody
})),
body: JSON.stringify(requestBody)
});
res.status(response.status);
const contentType = response.headers.get('content-type');
if (contentType) {
res.type(contentType);
}
res.send(await response.text());
} catch (error) {
logBridge('Player control sync relay failed', {
error: error && error.message ? error.message : String(error)
});
next(error);
}
});
fs.mkdirSync(config.mediaDir, { recursive: true }); fs.mkdirSync(config.mediaDir, { recursive: true });
server.listen(config.port, function () { server.listen(config.port, function () {
+12
View File
@@ -17,6 +17,7 @@ const { ensureFontLibrary } = require('#src/web/lib/media/font-library');
const { createRequestAuthHeaders } = require('#src/request-auth'); const { createRequestAuthHeaders } = require('#src/request-auth');
const { withClientNameReservation } = require('#src/data/client-name-check'); const { withClientNameReservation } = require('#src/data/client-name-check');
const { getConfiguredPlayerIdentifier, recordPlayerHeartbeat } = require('#src/data/player-registry'); const { getConfiguredPlayerIdentifier, recordPlayerHeartbeat } = require('#src/data/player-registry');
const { createLocalControlService } = require('./player/local-control');
// Player runtime, media API, and websocket wiring. // Player runtime, media API, and websocket wiring.
@@ -94,6 +95,15 @@ async function start() {
const server = http.createServer(app); const server = http.createServer(app);
playerRuntime.installWebsocket(server); playerRuntime.installWebsocket(server);
app.use(express.json()); app.use(express.json());
const localControlService = createLocalControlService({
app: app,
server: server,
pool: pool,
playerRuntime: playerRuntime,
playerIdentifier: PLAYER_DEVICE_ID,
cachePath: path.join(MEDIA_DIR, 'player-cache', 'local-control-users.json'),
cacheMaxAgeMs: Number(process.env.LOCAL_CONTROL_CACHE_MAX_AGE_MS || 72 * 60 * 60 * 1000)
});
let hasLoggedPlayerStartup = false; let hasLoggedPlayerStartup = false;
@@ -364,6 +374,8 @@ async function start() {
onPlayerPublicBaseUrl: setPlayerPublicBaseUrl onPlayerPublicBaseUrl: setPlayerPublicBaseUrl
}); });
await localControlService.loadCache();
function createThinClientWebSocketUrl() { function createThinClientWebSocketUrl() {
if (!BRIDGE_PUBLIC_URL) { if (!BRIDGE_PUBLIC_URL) {
return null; return null;
+579
View File
@@ -0,0 +1,579 @@
// Player-local control login, cache, and command routes.
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { WebSocketServer, WebSocket } = require('ws');
const { verifyPassword, createSessionToken, hashSessionToken } = require('#src/auth');
const { verifyRequestAuth } = require('#src/request-auth');
const DEFAULT_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
const DEFAULT_LOGIN_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
const DEFAULT_LOGIN_RATE_LIMIT_MAX_ATTEMPTS = 5;
const LOCAL_COMMANDS = new Set(['reload', 'previous', 'next', 'pause', 'blackout']);
function parseCookies(value) {
return String(value || '').split(';').reduce(function (cookies, part) {
const separator = part.indexOf('=');
if (separator === -1) {
return cookies;
}
const name = decodeURIComponent(part.slice(0, separator).trim());
const cookieValue = decodeURIComponent(part.slice(separator + 1).trim());
if (name) {
cookies[name] = cookieValue;
}
return cookies;
}, {});
}
function serializeCookie(name, value, maxAgeMs) {
return `${encodeURIComponent(name)}=${encodeURIComponent(value)}; Max-Age=${Math.max(0, Math.trunc(Number(maxAgeMs) / 1000))}; Path=/local-control; HttpOnly; SameSite=Lax`;
}
function fingerprintUsername(username) {
return crypto.createHash('sha256').update(String(username || '').trim()).digest('hex');
}
function getSessionCookieName(playerIdentifier) {
const suffix = String(playerIdentifier || '').trim().replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 128) || 'default';
return `pulse_local_control_${suffix}_session`;
}
function createLocalControlService(options) {
const app = options && options.app;
const server = options && options.server;
const playerRuntime = options && options.playerRuntime;
const pool = options && options.pool;
const cachePath = path.resolve(String(options && options.cachePath || 'player-cache/local-control-users.json'));
const sessionCookieName = getSessionCookieName(options && options.playerIdentifier);
const cacheMaxAgeMs = Number(options && options.cacheMaxAgeMs) > 0
? Number(options.cacheMaxAgeMs)
: DEFAULT_CACHE_MAX_AGE_MS;
const loginRateLimitWindowMs = Number(options && options.loginRateLimitWindowMs) > 0
? Number(options.loginRateLimitWindowMs)
: DEFAULT_LOGIN_RATE_LIMIT_WINDOW_MS;
const loginRateLimitMaxAttempts = Number(options && options.loginRateLimitMaxAttempts) > 0
? Math.trunc(Number(options.loginRateLimitMaxAttempts))
: DEFAULT_LOGIN_RATE_LIMIT_MAX_ATTEMPTS;
const sessions = new Map();
const loginFailures = new Map();
const localControlSockets = new Set();
const localControlWs = new WebSocketServer({ noServer: true });
let cache = { syncedAt: null, users: [] };
function normalizeUsers(users) {
return (Array.isArray(users) ? users : []).map(function (user) {
return {
username_hash: String(user && (user.username_hash || fingerprintUsername(user.username)) || '').trim(),
password_hash: String(user && user.password_hash || '').trim(),
password_salt: String(user && user.password_salt || '').trim()
};
}).filter(function (user) {
return Boolean(user.username_hash && user.password_hash && user.password_salt);
});
}
async function loadCache() {
try {
const payload = JSON.parse(await fs.promises.readFile(cachePath, 'utf8'));
cache = {
syncedAt: String(payload && payload.syncedAt || '').trim() || null,
users: normalizeUsers(payload && payload.users)
};
} catch (_error) {
cache = { syncedAt: null, users: [] };
}
return cache;
}
async function saveUsers(users) {
const nextCache = {
syncedAt: new Date().toISOString(),
users: normalizeUsers(users)
};
const usersChanged = JSON.stringify(nextCache.users) !== JSON.stringify(cache.users);
await fs.promises.mkdir(path.dirname(cachePath), { recursive: true, mode: 0o700 });
const temporaryPath = `${cachePath}.${process.pid}.tmp`;
await fs.promises.writeFile(temporaryPath, JSON.stringify(nextCache, null, 2), { encoding: 'utf8', mode: 0o600 });
await fs.promises.chmod(temporaryPath, 0o600);
await fs.promises.rename(temporaryPath, cachePath);
await fs.promises.chmod(cachePath, 0o600);
cache = nextCache;
if (usersChanged) {
sessions.clear();
localControlSockets.forEach(function (socket) {
try {
socket.terminate();
} catch (_error) {
localControlSockets.delete(socket);
}
});
}
return cache;
}
function isCacheUsable() {
const syncedAt = new Date(cache.syncedAt || 0).getTime();
return Boolean(cache.users.length && Number.isFinite(syncedAt) && Date.now() - syncedAt <= cacheMaxAgeMs);
}
function getLoginRateLimitKey(req, username) {
const remoteAddress = String(req && req.socket && req.socket.remoteAddress || '').trim();
return `${remoteAddress}:${fingerprintUsername(username)}`;
}
function getLoginFailureTimestamps(key, now) {
const cutoff = now - loginRateLimitWindowMs;
const timestamps = (loginFailures.get(key) || []).filter(function (timestamp) {
return timestamp > cutoff;
});
if (timestamps.length) {
loginFailures.set(key, timestamps);
} else {
loginFailures.delete(key);
}
return timestamps;
}
function getLoginRateLimitRetryAfter(req, username) {
const now = Date.now();
const timestamps = getLoginFailureTimestamps(getLoginRateLimitKey(req, username), now);
if (timestamps.length < loginRateLimitMaxAttempts) {
return 0;
}
return Math.max(1, Math.ceil((timestamps[0] + loginRateLimitWindowMs - now) / 1000));
}
function recordLoginFailure(req, username) {
const key = getLoginRateLimitKey(req, username);
const timestamps = getLoginFailureTimestamps(key, Date.now());
timestamps.push(Date.now());
loginFailures.set(key, timestamps);
}
function clearLoginFailures(req, username) {
loginFailures.delete(getLoginRateLimitKey(req, username));
}
function getUserFromRequest(req) {
const cookies = parseCookies(req && req.headers && req.headers.cookie);
const token = String(cookies[sessionCookieName] || '').trim();
if (!token) {
return null;
}
const session = sessions.get(hashSessionToken(token));
if (!session || session.expiresAt <= Date.now()) {
sessions.delete(hashSessionToken(token));
return null;
}
return session.user;
}
function requireLocalAuth(req, res, next) {
const user = getUserFromRequest(req);
if (!user) {
return res.status(401).json({ error: 'Local control login required.' });
}
req.localControlUser = user;
return next();
}
async function getScreenNames(slugs) {
if (!pool || !Array.isArray(slugs) || !slugs.length) {
return new Map();
}
try {
const [rows] = await pool.query('SELECT slug, name FROM d_screens WHERE slug IN (?)', [slugs]);
return new Map((Array.isArray(rows) ? rows : []).map(function (row) {
return [String(row && row.slug || '').trim(), String(row && row.name || '').trim()];
}));
} catch (_error) {
return new Map();
}
}
async function getState() {
const slugs = playerRuntime.snapshotSlugs();
const screenNames = await getScreenNames(slugs);
return {
screens: slugs.map(function (slug) {
return { slug: slug, name: screenNames.get(slug) || slug, connections: playerRuntime.snapshotConnections(slug) };
}),
syncedAt: cache.syncedAt
};
}
function sendState(socket, state) {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'local-control-state', state: state }));
}
}
function broadcastState() {
if (!localControlSockets.size) {
return;
}
getState().then(function (state) {
localControlSockets.forEach(function (socket) { sendState(socket, state); });
}).catch(function () {});
}
function renderPage() {
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Local control</title><style>body{font-family:system-ui,sans-serif;background:#18212b;color:#f3f6f8;margin:0;padding:2rem}main{max-width:58rem;margin:auto}section{background:#24313d;border:1px solid #405160;padding:1rem;margin:1rem 0;border-radius:6px}input,button{font:inherit;padding:.55rem;margin:.25rem 0}input{width:100%;box-sizing:border-box;background:#16202a;color:#fff;border:1px solid #607384}button{cursor:pointer}table{width:100%;border-collapse:collapse}td,th{text-align:left;padding:.6rem;border-bottom:1px solid #405160}#message{min-height:1.4rem}</style></head><body><main><h1>Local control</h1><section id="login"><form id="login-form"><label>Username<input name="username" autocomplete="username" required></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button type="submit">Sign in</button></form></section><section id="controls" hidden><p id="message"></p><button id="logout" type="button">Sign out</button><table><thead><tr><th>Client</th><th>Screen</th><th>Actions</th></tr></thead><tbody id="clients"></tbody></table></section></main><script>(function(){var login=document.getElementById('login');var controls=document.getElementById('controls');var message=document.getElementById('message');var clients=document.getElementById('clients');function request(url,options){return fetch(url,options||{}).then(function(response){return response.json().catch(function(){return {};}).then(function(body){if(!response.ok){throw new Error(body.error||'Request failed.');}return body;});});}function showError(error){message.textContent=error.message||String(error);}function sendCommand(screen,connection,command){return request('/local-control/api/commands',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({slug:screen.slug,connectionId:connection.id,command:command})}).then(function(){message.textContent='Command sent.';}).catch(showError);}function render(state){login.hidden=true;controls.hidden=false;clients.textContent='';(state.screens||[]).forEach(function(screen){(screen.connections||[]).forEach(function(connection){var row=document.createElement('tr');[connection.clientName||connection.label||connection.clientId||'Client',screen.name||screen.slug].forEach(function(value){var cell=document.createElement('td');cell.textContent=value;row.appendChild(cell);});var cell=document.createElement('td');['Reload','Previous','Next','Pause','Blackout'].forEach(function(label){var action=document.createElement('button');action.type='button';action.textContent=label;action.addEventListener('click',function(){sendCommand(screen,connection,label.toLowerCase());});cell.appendChild(action);});row.appendChild(cell);clients.appendChild(row);});});}function load(){request('/local-control/api/state').then(render).catch(function(error){if(error.message.indexOf('login')!==-1){login.hidden=false;controls.hidden=true;}else{showError(error);}});}document.getElementById('login-form').addEventListener('submit',function(event){event.preventDefault();var data=new FormData(event.currentTarget);request('/local-control/api/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:data.get('username'),password:data.get('password')})}).then(load).catch(showError);});document.getElementById('logout').addEventListener('click',function(){request('/local-control/api/logout',{method:'POST'}).then(function(){location.reload();}).catch(showError);});load();setInterval(load,10000);}());</script></body></html>`;
}
function renderPageV2() {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Local Control</title>
<style>
:root { color-scheme: dark; --page: #111a22; --panel: #1c2934; --panel-soft: #223442; --line: #3a4b59; --text: #f3f6f8; --muted: #aab8c2; --accent: #72c7b8; }
* { box-sizing: border-box; }
body { margin: 0; min-width: 320px; padding: 1.25rem; background: var(--page) radial-gradient(circle at top, #243847 0, var(--page) 42rem) no-repeat; background-size: 100% 42rem; color: var(--text); font-family: system-ui, sans-serif; }
main { width: min(100%, 66rem); margin: 0 auto; }
header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; width: min(100%, 30rem); margin: 0 auto; padding: .25rem 0 1.25rem; }
header.wide { width: 100%; }
h1 { margin: 0; font-size: clamp(1.45rem, 4vw, 2rem); letter-spacing: .01em; }
section { background: color-mix(in srgb, var(--panel) 94%, transparent); border: 1px solid var(--line); border-radius: 10px; box-shadow: 0 1rem 2rem rgb(0 0 0 / 12%); }
#login { max-width: 30rem; margin: 0 auto; padding: 1.25rem; }
form { display: grid; gap: .8rem; }
label { display: grid; gap: .35rem; color: var(--muted); font-size: .9rem; }
input, button { font: inherit; }
input { width: 100%; padding: .7rem .75rem; border: 1px solid #607384; border-radius: 6px; background: #13202a; color: var(--text); }
button { min-height: 2.5rem; padding: .55rem .8rem; border: 1px solid #6d8797; border-radius: 6px; background: var(--panel-soft); color: var(--text); cursor: pointer; }
button:hover, button:focus-visible { border-color: var(--accent); outline: 2px solid rgb(114 199 184 / 25%); outline-offset: 1px; }
#logout { flex: 0 0 auto; }
#controls { overflow: hidden; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: .85rem 1rem; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--line); }
th { color: var(--muted); font-size: .78rem; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; }
tbody tr:last-child td { border-bottom: 0; }
td:first-child { width: 31%; font-weight: 650; }
.client-cell { position: relative; padding-right: 6rem !important; }
td:nth-child(2) { width: 22%; color: var(--muted); }
td:nth-child(3) { width: 22%; color: var(--muted); }
.actions { display: grid; gap: .3rem; min-width: 14rem; }
.action-row { display: flex; flex-wrap: nowrap; gap: .3rem; }
.action-row button { flex: 1 1 0; margin: 0; min-height: 2.1rem; padding: .35rem .55rem; border: 0; font-size: .84rem; white-space: nowrap; }
.btn-danger { background: #dc3545; color: #fff; }
.btn-warning { background: #ffc107; color: #111; }
.btn-info { background: #0dcaf0; color: #111; }
.btn-secondary { background: #6c757d; color: #fff; }
.btn-success { background: #198754; color: #fff; }
.button-icon { display: inline-flex; width: 1rem; height: 1rem; margin-right: .35rem; vertical-align: -.15rem; }
.button-icon svg { width: 100%; height: 100%; fill: currentColor; }
.state-badge { position: absolute; top: .85rem; right: 1rem; padding: .2rem .45rem; border: 1px solid #d8a95b; border-radius: 999px; color: #ffd98b; font-size: .72rem; font-weight: 650; letter-spacing: .03em; }
.state-badge.blackout { border-color: #9aa7b2; color: #d9e0e5; }
@media (max-width: 600px) {
body { padding: .75rem; }
header { padding-bottom: 1rem; }
#login { padding: 1rem; }
table, thead, tbody, tr, td { display: block; }
thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
tbody { padding: .55rem; }
tr { margin: .55rem 0; padding: .85rem; border: 1px solid var(--line); border-radius: 8px; background: var(--panel-soft); }
td, td:first-child, td:nth-child(2), td:nth-child(3) { width: auto; padding: .15rem 0; border: 0; }
.client-cell { padding-right: 5.5rem !important; }
.client-cell .state-badge { top: .15rem; right: 0; }
td::before { display: block; margin-bottom: .15rem; color: var(--muted); font-size: .72rem; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; content: attr(data-label); }
td:first-child { font-size: 1.05rem; }
td:nth-child(2) { margin-top: .6rem; }
td:last-child { margin-top: .8rem; }
.actions { gap: .25rem; overflow-x: auto; padding-bottom: .2rem; }
.action-row { gap: .25rem; }
.action-row button { padding: .35rem .5rem; font-size: .76rem; }
}
</style>
</head>
<body>
<main>
<header id="page-header"><h1>Local control</h1><button id="logout" type="button" hidden>Sign out</button></header>
<section id="login"><form id="login-form"><label>Username<input name="username" autocomplete="username" required></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button type="submit">Sign in</button></form></section>
<section id="controls" hidden><table><thead><tr><th>Client</th><th>Screen</th><th>Current Slide</th><th>Actions</th></tr></thead><tbody id="clients"></tbody></table></section>
</main>
<script>
(function () {
var login = document.getElementById('login');
var controls = document.getElementById('controls');
var pageHeader = document.getElementById('page-header');
var logout = document.getElementById('logout');
var clients = document.getElementById('clients');
var socket = null;
var reconnectTimer = null;
function request(url, options) {
return fetch(url, options || {}).then(function (response) {
return response.json().catch(function () { return {}; }).then(function (body) {
if (!response.ok) { throw new Error(body.error || 'Request failed.'); }
return body;
});
});
}
function showError(error) { console.error(error); }
function getActionClass(command, connection) {
if (command === 'reload') { return 'btn-danger'; }
if (command === 'previous' || command === 'next') { return 'btn-warning'; }
if (command === 'pause') { return 'btn-info'; }
return connection.blackout ? 'btn-success' : 'btn-secondary';
}
function getActionContent(command, connection) {
var icons = {
reload: '<path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41m-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9"/><path fill-rule="evenodd" d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5 5 0 0 0 8 3M3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9z"/>',
previous: '<path d="M.5 3.5A.5.5 0 0 0 0 4v8a.5.5 0 0 0 1 0V8.753l6.267 3.636c.54.313 1.233-.066 1.233-.697v-2.94l6.267 3.636c.54.314 1.233-.065 1.233-.696V4.308c0-.63-.693-1.01-1.233-.696L8.5 7.248v-2.94c0-.63-.692-1.01-1.233-.696L1 7.248V4a.5.5 0 0 0-.5-.5"/>',
next: '<path d="M15.5 3.5a.5.5 0 0 1 .5.5v8a.5.5 0 0 1-1 0V8.753l-6.267 3.636c-.54.313-1.233-.066-1.233-.697v-2.94l-6.267 3.636C.693 12.703 0 12.324 0 11.693V4.308c0-.63.693-1.01 1.233-.696L7.5 7.248v-2.94c0-.63.693-1.01 1.233-.696L15 7.248V4a.5.5 0 0 1 .5-.5"/>',
pause: connection.paused ? '<path d="m11.596 8.697-6.363 3.692c-.54.313-1.233-.066-1.233-.697V4.308c0-.63.692-1.01 1.233-.696l6.363 3.692a.802.802 0 0 1 0 1.393"/>' : '<path d="M5.5 3.5A1.5 1.5 0 0 1 7 5v6a1.5 1.5 0 0 1-3 0V5a1.5 1.5 0 0 1 1.5-1.5m5 0A1.5 1.5 0 0 1 12 5v6a1.5 1.5 0 0 1-3 0V5a1.5 1.5 0 0 1 1.5-1.5"/>',
blackout: connection.blackout ? '<path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8M1.173 8a13 13 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5s3.879 1.168 5.168 2.457A13 13 0 0 1 14.828 8q-.086.13-.195.288c-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5s-3.879-1.168-5.168-2.457A13 13 0 0 1 1.172 8z"/><path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5M4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0"/>' : '<path d="M13.359 11.238C15.06 9.72 16 8 16 8s-3-5.5-8-5.5a7 7 0 0 0-2.79.588l.77.771A6 6 0 0 1 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13 13 0 0 1 14.828 8q-.086.13-.195.288c-.335.48-.83 1.12-1.465 1.755q-.247.248-.517.486z"/><path d="M11.297 9.176a3.5 3.5 0 0 0-4.474-4.474l.823.823a2.5 2.5 0 0 1 2.829 2.829zm-2.943 1.299.822.822a3.5 3.5 0 0 1-4.474-4.474l.823.823a2.5 2.5 0 0 0 2.829 2.829"/><path d="M3.35 5.47q-.27.24-.518.487A13 13 0 0 0 1.172 8l.195.288c.335.48.83 1.12 1.465 1.755C4.121 11.332 5.881 12.5 8 12.5c.716 0 1.39-.133 2.02-.36l.77.772A7 7 0 0 1 8 13.5C3 13.5 0 8 0 8s.939-1.721 2.641-3.238l.708.709zm10.296 8.884-12-12 .708-.708 12 12z"/>'
};
var text = command === 'pause' ? (connection.paused ? 'Resume' : 'Pause') : command === 'blackout' ? (connection.blackout ? 'Restore' : 'Blackout') : '';
return '<span class="button-icon" aria-hidden="true"><svg viewBox="0 0 16 16" focusable="false">' + icons[command] + '</svg></span>' + text;
}
function addStateBadge(clientCell, connection) {
if (!connection.paused && !connection.blackout) { return; }
var badge = document.createElement('span');
badge.className = 'state-badge' + (connection.blackout ? ' blackout' : '');
badge.textContent = connection.blackout ? 'Blackout' : 'Paused';
badge.setAttribute('aria-label', connection.blackout ? 'Blackout' : 'Paused');
clientCell.appendChild(badge);
}
function updateConnectionRow(row, connection) {
var clientCell = row.children[0];
var stateBadge = clientCell.querySelector('.state-badge');
if (stateBadge) { stateBadge.remove(); }
addStateBadge(clientCell, connection);
var pauseButton = row.querySelector('button[data-command="pause"]');
pauseButton.className = 'local-action ' + getActionClass('pause', connection);
pauseButton.innerHTML = getActionContent('pause', connection);
pauseButton.setAttribute('aria-label', connection.paused ? 'Resume client' : 'Pause client');
pauseButton.title = connection.paused ? 'Resume client' : 'Pause client';
var blackoutButton = row.querySelector('button[data-command="blackout"]');
blackoutButton.className = 'local-action ' + getActionClass('blackout', connection);
blackoutButton.innerHTML = getActionContent('blackout', connection);
blackoutButton.setAttribute('aria-label', connection.blackout ? 'Restore client' : 'Blackout client');
blackoutButton.title = connection.blackout ? 'Restore client' : 'Blackout client';
}
function sendCommand(screen, connection, command, row) {
return request('/local-control/api/commands', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ slug: screen.slug, connectionId: connection.id, command: command }) })
.then(function () {
if (command === 'pause') { connection.paused = !connection.paused; }
if (command === 'blackout') { connection.blackout = !connection.blackout; }
updateConnectionRow(row, connection);
})
.catch(showError);
}
function render(state) {
login.hidden = true;
controls.hidden = false;
logout.hidden = false;
pageHeader.className = 'wide';
clients.textContent = '';
(state.screens || []).forEach(function (screen) {
(screen.connections || []).forEach(function (connection) {
var row = document.createElement('tr');
var clientCell = document.createElement('td');
clientCell.className = 'client-cell';
clientCell.dataset.label = 'Client';
clientCell.textContent = connection.clientName || connection.label || connection.clientId || 'Client';
addStateBadge(clientCell, connection);
row.appendChild(clientCell);
var screenCell = document.createElement('td');
screenCell.dataset.label = 'Screen';
screenCell.textContent = screen.name || screen.slug;
row.appendChild(screenCell);
var slideCell = document.createElement('td');
slideCell.dataset.label = 'Current Slide';
slideCell.textContent = connection.currentSlideTitle || 'No slide currently showing';
row.appendChild(slideCell);
var actionCell = document.createElement('td');
actionCell.dataset.label = 'Actions';
actionCell.className = 'actions';
[['Reload', 'Previous', 'Next'], ['Pause', 'Blackout']].forEach(function (labels) {
var actionRow = document.createElement('div');
actionRow.className = 'action-row';
labels.forEach(function (label) {
var action = document.createElement('button');
action.type = 'button';
action.dataset.command = label.toLowerCase();
action.className = 'local-action ' + getActionClass(label.toLowerCase(), connection);
action.innerHTML = getActionContent(label.toLowerCase(), connection);
action.setAttribute('aria-label', label + ' client');
action.title = label + ' client';
action.addEventListener('click', function () { sendCommand(screen, connection, label.toLowerCase(), row); });
actionRow.appendChild(action);
});
actionCell.appendChild(actionRow);
});
row.appendChild(actionCell);
clients.appendChild(row);
});
});
}
function load() {
request('/local-control/api/state').then(function (state) {
render(state);
connectSocket();
}).catch(function (error) {
if (error.message.indexOf('login') !== -1) { login.hidden = false; controls.hidden = true; logout.hidden = true; pageHeader.className = ''; }
else { showError(error); }
});
}
function scheduleReconnect() {
if (reconnectTimer || login.hidden === false) { return; }
reconnectTimer = window.setTimeout(function () {
reconnectTimer = null;
connectSocket();
}, 5000);
}
function connectSocket() {
if (!window.WebSocket || !login.hidden || (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING))) { return; }
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
socket = new WebSocket(protocol + '//' + window.location.host + '/local-control/ws');
socket.onmessage = function (event) {
try {
var payload = JSON.parse(String(event.data || '{}'));
if (payload && payload.type === 'local-control-state') { render(payload.state); }
} catch (_error) {
}
};
socket.onclose = function () { socket = null; scheduleReconnect(); };
socket.onerror = function () { try { socket.close(); } catch (_error) {} };
}
document.getElementById('login-form').addEventListener('submit', function (event) {
event.preventDefault();
var data = new FormData(event.currentTarget);
request('/local-control/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: data.get('username'), password: data.get('password') }) }).then(load).catch(showError);
});
logout.addEventListener('click', function () { request('/local-control/api/logout', { method: 'POST' }).then(function () { location.reload(); }).catch(showError); });
load();
if (!window.WebSocket) { setInterval(load, 10000); }
}());
</script>
</body>
</html>`;
}
if (!app || !playerRuntime) {
throw new Error('createLocalControlService requires app and playerRuntime.');
}
if (server) {
server.on('upgrade', function (request, socket, head) {
let pathname = '';
try {
pathname = new URL(request.url, 'http://localhost').pathname;
} catch (_error) {
socket.destroy();
return;
}
if (pathname !== '/local-control/ws') {
return;
}
if (!getUserFromRequest(request)) {
socket.destroy();
return;
}
localControlWs.handleUpgrade(request, socket, head, function (ws) {
localControlWs.emit('connection', ws, request);
});
});
localControlWs.on('connection', function (socket) {
localControlSockets.add(socket);
getState().then(function (state) { sendState(socket, state); }).catch(function () {});
socket.on('close', function () { localControlSockets.delete(socket); });
socket.on('error', function () { localControlSockets.delete(socket); });
});
if (typeof playerRuntime.subscribeSnapshot === 'function') {
playerRuntime.subscribeSnapshot(broadcastState);
}
}
app.get('/local-control', function (req, res) {
res.set('Cache-Control', 'no-store');
res.type('html').send(renderPageV2());
});
app.post('/local-control/api/login', async function (req, res, next) {
try {
await loadCache();
if (!isCacheUsable()) {
return res.status(503).json({ error: 'Local control authorization is unavailable.' });
}
const username = String(req.body && req.body.username || '').trim();
const retryAfter = getLoginRateLimitRetryAfter(req, username);
if (retryAfter) {
res.set('Retry-After', String(retryAfter));
return res.status(429).json({ error: 'Too many local control login attempts. Try again later.' });
}
const user = cache.users.find(function (candidate) {
return candidate.username_hash === fingerprintUsername(username);
});
if (!user || !verifyPassword(String(req.body && req.body.password || ''), user)) {
recordLoginFailure(req, username);
return res.status(401).json({ error: 'Invalid local control credentials.' });
}
clearLoginFailures(req, username);
const token = createSessionToken();
sessions.set(hashSessionToken(token), { user: { id: user.id, name: user.name, username: user.username }, expiresAt: Date.now() + 12 * 60 * 60 * 1000 });
res.set('Set-Cookie', serializeCookie(sessionCookieName, token, 12 * 60 * 60 * 1000));
return res.json({ ok: true });
} catch (error) {
return next(error);
}
});
app.post('/local-control/api/logout', function (req, res) {
const cookies = parseCookies(req.headers && req.headers.cookie);
sessions.delete(hashSessionToken(String(cookies[sessionCookieName] || '').trim()));
res.set('Set-Cookie', serializeCookie(sessionCookieName, '', 0));
return res.json({ ok: true });
});
app.get('/local-control/api/state', requireLocalAuth, async function (_req, res, next) {
try {
return res.json(await getState());
} catch (error) {
return next(error);
}
});
app.post('/local-control/api/commands', requireLocalAuth, async function (req, res, next) {
try {
const body = req.body && typeof req.body === 'object' ? req.body : {};
const command = String(body.command || '').trim().toLowerCase();
const slug = String(body.slug || '').trim();
const connectionId = String(body.connectionId || '').trim();
if (!LOCAL_COMMANDS.has(command) || !slug || !connectionId) {
return res.status(400).json({ error: 'A valid local client command is required.' });
}
const sent = await playerRuntime.sendCommandToConnection(slug, connectionId, { command: command, screenSlug: slug, connectionId: connectionId });
if (!sent) {
return res.status(409).json({ error: 'Local client is not connected.' });
}
return res.json({ ok: true });
} catch (error) {
return next(error);
}
});
app.post('/api/internal/sync/player-control', function (req, res) {
if (!verifyRequestAuth(req)) {
return res.status(401).json({ error: 'Request authentication required.' });
}
return saveUsers(req.body && req.body.users).then(function () {
return res.json({ ok: true, syncedAt: cache.syncedAt, userCount: cache.users.length });
}).catch(function (error) {
return res.status(500).json({ error: error.message || 'Unable to save local control users.' });
});
});
return {
loadCache: loadCache,
saveUsers: saveUsers,
isCacheUsable: isCacheUsable,
getUserFromRequest: getUserFromRequest
};
}
module.exports = { createLocalControlService: createLocalControlService };
+39
View File
@@ -32,6 +32,45 @@ body.onboarding-page #app {
position: relative; position: relative;
} }
.api-progress {
--bs-progress-height: 1rem;
--bs-progress-font-size: 0.75rem;
--bs-border-radius: 0.375rem;
--bs-progress-border-radius: 0.375rem;
display: flex;
width: 100%;
box-sizing: border-box;
height: var(--bs-progress-height);
overflow: hidden;
font-size: var(--bs-progress-font-size);
border-radius: var(--bs-progress-border-radius);
}
.api-progress > .progress-bar {
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
color: #fff;
text-align: center;
white-space: nowrap;
background-color: #0d6efd;
}
.api-progress > .progress-bar-striped {
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-size: var(--bs-progress-height) var(--bs-progress-height);
}
.api-progress > .progress-bar-animated {
animation: api-progress-bar-stripes 1s linear infinite;
}
@keyframes api-progress-bar-stripes {
from { background-position-x: var(--bs-progress-height); }
to { background-position-x: 0; }
}
.onboarding-shell { .onboarding-shell {
min-height: 100%; min-height: 100%;
display: flex; display: flex;
+3
View File
@@ -68,6 +68,9 @@ function substituteApiVariables(html, item, sourceId) {
} }
var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression); var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression);
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(expression)) {
return placeholderUtils.renderProgressPlaceholder(item, expression);
}
if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) { if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) {
var imageSource = placeholderUtils.formatPlaceholderValue(resolved); var imageSource = placeholderUtils.formatPlaceholderValue(resolved);
var source = getApiSourceById(sourceId); var source = getApiSourceById(sourceId);
+3
View File
@@ -74,6 +74,9 @@ function substituteRssVariables(html, item, feedId) {
return ''; return '';
} }
var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression); var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression);
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(expression)) {
return placeholderUtils.renderProgressPlaceholder(item, expression);
}
if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) { if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) {
var imageSource = placeholderUtils.formatPlaceholderValue(resolved); var imageSource = placeholderUtils.formatPlaceholderValue(resolved);
var feed = getRssFeedById(feedId); var feed = getRssFeedById(feedId);
+4 -5
View File
@@ -2,7 +2,6 @@
var registry = window.pulsePlayerRegionTypes; var registry = window.pulsePlayerRegionTypes;
var placeholderUtils = window.placeholderUtils || {}; var placeholderUtils = window.placeholderUtils || {};
var DEFAULT_FORMAT = '{{hh}}:{{mm}}';
var DEFAULT_STYLE = { var DEFAULT_STYLE = {
font_family: 'Arial', font_family: 'Arial',
font_size: 32, font_size: 32,
@@ -204,7 +203,7 @@ function getTimeDateFormattedParts(timeZone, date) {
dddd: toTitleCase(getPart(weekdayLong, 'weekday')), dddd: toTitleCase(getPart(weekdayLong, 'weekday')),
MMM: toTitleCase(getPart(monthShort, 'month')), MMM: toTitleCase(getPart(monthShort, 'month')),
MMMM: toTitleCase(getPart(monthLong, 'month')), MMMM: toTitleCase(getPart(monthLong, 'month')),
a: toTitleCase(getPart(ampm, 'dayPeriod')), a: String(getPart(ampm, 'dayPeriod') || '').toLowerCase(),
tz: getPart(timezoneShort, 'timeZoneName'), tz: getPart(timezoneShort, 'timeZoneName'),
tz_long: resolvedTimeZone, tz_long: resolvedTimeZone,
date: getPart(numericParts, 'year') + '-' + getPart(numericParts, 'month') + '-' + getPart(numericParts, 'day'), date: getPart(numericParts, 'year') + '-' + getPart(numericParts, 'month') + '-' + getPart(numericParts, 'day'),
@@ -223,7 +222,7 @@ function resolveTimeDateTemplatePlaceholder(values, expression) {
} }
function renderTimeDateTemplate(format, timeZone, date) { function renderTimeDateTemplate(format, timeZone, date) {
var template = String(format || '').trim() || DEFAULT_FORMAT; var template = String(format || '').trim();
var values = getTimeDateFormattedParts(timeZone, date); var values = getTimeDateFormattedParts(timeZone, date);
return template.replace(/\{\{\s*([a-zA-Z0-9_.()\-]+)\s*\}\}/g, function (_match, key) { return template.replace(/\{\{\s*([a-zA-Z0-9_.()\-]+)\s*\}\}/g, function (_match, key) {
return String(resolveTimeDateTemplatePlaceholder(values, key, { timeZone: timeZone }) || ''); return String(resolveTimeDateTemplatePlaceholder(values, key, { timeZone: timeZone }) || '');
@@ -243,7 +242,7 @@ function getTextStyle(regionContent, region) {
function renderTimeDateRegion(region, regionContent) { function renderTimeDateRegion(region, regionContent) {
var content = regionContent && typeof regionContent === 'object' ? regionContent : {}; var content = regionContent && typeof regionContent === 'object' ? regionContent : {};
var format = String(content.value !== undefined ? content.value : content.text || '').trim() || DEFAULT_FORMAT; var format = String(content.value !== undefined ? content.value : content.text || '').trim();
var timeZone = resolveTimeZone(content.timezone || content.time_zone || ''); var timeZone = resolveTimeZone(content.timezone || content.time_zone || '');
var style = getTextStyle(content, region); var style = getTextStyle(content, region);
var fontFamily = style.font_family ? 'font-family:' + escapeHtml(style.font_family) + ';' : ''; var fontFamily = style.font_family ? 'font-family:' + escapeHtml(style.font_family) + ';' : '';
@@ -259,7 +258,7 @@ function updateTimeDateRegion(element) {
return; return;
} }
var format = String(element.dataset.timeDateFormat || '').trim() || DEFAULT_FORMAT; var format = String(element.dataset.timeDateFormat || '').trim();
var timeZone = String(element.dataset.timeDateTimezone || '').trim(); var timeZone = String(element.dataset.timeDateTimezone || '').trim();
var scaleWrapper = element.querySelector('.template-region-text-scale'); var scaleWrapper = element.querySelector('.template-region-text-scale');
if (!scaleWrapper) { if (!scaleWrapper) {
+3
View File
@@ -13,6 +13,9 @@ function substituteTimetableVariables(html, entry) {
return ''; return '';
} }
if (typeof window.placeholderUtils.isProgressPlaceholderExpression === 'function' && window.placeholderUtils.isProgressPlaceholderExpression(expression)) {
return window.placeholderUtils.renderProgressPlaceholder(entry, expression);
}
return escapeHtml(window.placeholderUtils.formatPlaceholderValue(window.placeholderUtils.resolvePlaceholderExpression(entry, expression))); return escapeHtml(window.placeholderUtils.formatPlaceholderValue(window.placeholderUtils.resolvePlaceholderExpression(entry, expression)));
}); });
} }
+5 -1
View File
@@ -51,6 +51,9 @@ function substituteWeatherVariables(html, value) {
if (!value || typeof value !== 'object' || typeof weatherPlaceholderUtils.resolvePlaceholderExpression !== 'function' || typeof weatherPlaceholderUtils.formatPlaceholderValue !== 'function') return ''; if (!value || typeof value !== 'object' || typeof weatherPlaceholderUtils.resolvePlaceholderExpression !== 'function' || typeof weatherPlaceholderUtils.formatPlaceholderValue !== 'function') return '';
var rawExpression = String(expression).trim(); var rawExpression = String(expression).trim();
var normalizedExpression = normalizeWeatherExpression(rawExpression); var normalizedExpression = normalizeWeatherExpression(rawExpression);
if (typeof weatherPlaceholderUtils.isProgressPlaceholderExpression === 'function' && weatherPlaceholderUtils.isProgressPlaceholderExpression(rawExpression)) {
return weatherPlaceholderUtils.renderProgressPlaceholder(value, rawExpression);
}
var iconMatch = normalizedExpression.match(/^(?:current\.weather_code|daily\.weather_code\.\d+|hourly\.weather_code\.\d+)\.icon(?:\((\d+)(?:\s*,\s*(\d+))?\))?$/); var iconMatch = normalizedExpression.match(/^(?:current\.weather_code|daily\.weather_code\.\d+|hourly\.weather_code\.\d+)\.icon(?:\((\d+)(?:\s*,\s*(\d+))?\))?$/);
if (iconMatch) { if (iconMatch) {
var codeExpression = normalizedExpression.replace(/\.icon(?:\(.*\))?$/, ''); var codeExpression = normalizedExpression.replace(/\.icon(?:\(.*\))?$/, '');
@@ -66,6 +69,8 @@ function substituteWeatherVariables(html, value) {
} }
function renderWeatherRegion(region, regionContent) { function renderWeatherRegion(region, regionContent) {
var value = String(regionContent && regionContent.value || '');
if (!value.trim()) return '';
var location = getWeatherLocation(regionContent && regionContent.weather_location_id); var location = getWeatherLocation(regionContent && regionContent.weather_location_id);
var snapshot = location && location.responseJson && typeof location.responseJson === 'object' ? location.responseJson : null; var snapshot = location && location.responseJson && typeof location.responseJson === 'object' ? location.responseJson : null;
var width = Math.max(1, Math.round(Number(region && region.pixelWidth) || 1)); var width = Math.max(1, Math.round(Number(region && region.pixelWidth) || 1));
@@ -74,7 +79,6 @@ function renderWeatherRegion(region, regionContent) {
var style = 'width:' + width + 'px;height:' + height + 'px;transform:scale(' + scale + ');transform-origin:top left;overflow:hidden;'; var style = 'width:' + width + 'px;height:' + height + 'px;transform:scale(' + scale + ');transform-origin:top left;overflow:hidden;';
if (!location || !snapshot) return '<div class="template-region weather" style="' + region.baseStyle + '"><div style="' + style + '"></div></div>'; if (!location || !snapshot) return '<div class="template-region weather" style="' + region.baseStyle + '"><div style="' + style + '"></div></div>';
var current = snapshot.current || {}; var current = snapshot.current || {};
var value = String(regionContent && regionContent.value || '');
if (value) { if (value) {
var weatherData = withWeatherUnits(snapshot, location); var weatherData = withWeatherUnits(snapshot, location);
var fontSize = Math.max(8, Number(regionContent && regionContent.font_size || region && (region.font_size || region.fontSize) || 32) || 32); var fontSize = Math.max(8, Number(regionContent && regionContent.font_size || region && (region.font_size || region.fontSize) || 32) || 32);
+23 -1
View File
@@ -32,6 +32,7 @@ function createPlayerRuntime(options) {
const connectionsBySlug = new Map(); const connectionsBySlug = new Map();
const dashboardListenersBySlug = new Map(); const dashboardListenersBySlug = new Map();
const announcementListenersBySlug = new Map(); const announcementListenersBySlug = new Map();
const snapshotListeners = new Set();
const pendingCommandAcks = new Map(); const pendingCommandAcks = new Map();
const wss = new WebSocketServer({ noServer: true }); const wss = new WebSocketServer({ noServer: true });
const staleConnectionMs = Number(options && options.staleConnectionMs) > 0 const staleConnectionMs = Number(options && options.staleConnectionMs) > 0
@@ -379,6 +380,12 @@ function createPlayerRuntime(options) {
} catch (_error) { } catch (_error) {
} }
} }
snapshotListeners.forEach(function (listener) {
try {
listener({ slug: key, connections: connections });
} catch (_error) {
}
});
if (!bucket || !bucket.size) { if (!bucket || !bucket.size) {
return; return;
} }
@@ -503,6 +510,10 @@ function createPlayerRuntime(options) {
const playerMatch = pathname.match(/^\/ws\/screens\/([^/]+)$/); const playerMatch = pathname.match(/^\/ws\/screens\/([^/]+)$/);
const announcementMatch = pathname.match(/^\/ws\/screens\/([^/]+)\/announcements$/); const announcementMatch = pathname.match(/^\/ws\/screens\/([^/]+)\/announcements$/);
if (pathname === '/local-control/ws') {
return;
}
if (!dashboardMatch && !playerMatch && !announcementMatch) { if (!dashboardMatch && !playerMatch && !announcementMatch) {
socket.destroy(); socket.destroy();
return; return;
@@ -720,6 +731,16 @@ function createPlayerRuntime(options) {
server.on('upgrade', handleUpgrade); server.on('upgrade', handleUpgrade);
} }
function subscribeSnapshot(listener) {
if (typeof listener !== 'function') {
return function () {};
}
snapshotListeners.add(listener);
return function () {
snapshotListeners.delete(listener);
};
}
return { return {
installWebsocket: installWebsocket, installWebsocket: installWebsocket,
broadcastAnnouncementRefresh: broadcastAnnouncementRefresh, broadcastAnnouncementRefresh: broadcastAnnouncementRefresh,
@@ -728,7 +749,8 @@ function createPlayerRuntime(options) {
snapshotSlugs: snapshotSlugs, snapshotSlugs: snapshotSlugs,
isClientNameAvailableOnScreen: isClientNameAvailableOnScreen, isClientNameAvailableOnScreen: isClientNameAvailableOnScreen,
sendCommandToConnection: sendCommandToConnection, sendCommandToConnection: sendCommandToConnection,
broadcastCommand: broadcastCommand broadcastCommand: broadcastCommand,
subscribeSnapshot: subscribeSnapshot
}; };
} }
+21
View File
@@ -81,6 +81,16 @@ const PERMISSION_SECTIONS = [
{ key: 'delete', name: 'Delete', description: 'Delete slide templates.' } { key: 'delete', name: 'Delete', description: 'Delete slide templates.' }
] ]
}, },
{
key: 'media-library',
order: 45,
name: 'Media library',
permissions: [
{ key: 'read', name: 'Read', description: 'View shared media assets.' },
{ key: 'create', name: 'Create', description: 'Upload shared media assets.' },
{ key: 'delete', name: 'Delete', description: 'Delete unused shared media assets.' }
]
},
{ {
key: 'canvas-sizes', key: 'canvas-sizes',
order: 50, order: 50,
@@ -191,6 +201,17 @@ const PERMISSION_SECTIONS = [
{ key: 'delete', name: 'Delete', description: 'Delete users.' } { key: 'delete', name: 'Delete', description: 'Delete users.' }
] ]
}, },
{
key: 'invitations',
order: 15,
name: 'Invitations',
permissions: [
{ key: 'read', name: 'Read', description: 'View pending user invitations.' },
{ key: 'create', name: 'Create', description: 'Send new user invitations.' },
{ key: 'delete', name: 'Delete', description: 'Delete pending user invitations.' },
{ key: 'allow', name: 'Allow', description: 'Resend pending user invitations.' }
]
},
{ {
key: 'rbac', key: 'rbac',
order: 20, order: 20,
+8 -2
View File
@@ -6,7 +6,7 @@ const multer = require('multer');
const fs = require('fs'); const fs = require('fs');
const crypto = require('crypto'); const crypto = require('crypto');
const common = require('./common'); const common = require('./common');
const { verifyPassword, createSessionToken, hashSessionToken, hashPassword, validatePasswordStrength } = require('#src/auth'); const { verifyPassword, createSessionToken, hashSessionToken, hashPassword, validatePasswordStrength, createOneTimeToken } = require('#src/auth');
const pages = require('#src/web/pages'); const pages = require('#src/web/pages');
const registerMiddleware = require('#src/web/middleware'); const registerMiddleware = require('#src/web/middleware');
const registerNotFoundHandler = require('#src/web/middleware/not-found'); const registerNotFoundHandler = require('#src/web/middleware/not-found');
@@ -23,8 +23,9 @@ const { requirePermission: createRequirePermission, PERMISSION_DENIED_MESSAGE }
const { rbacData } = require('#src/web/lib/auth'); const { rbacData } = require('#src/web/lib/auth');
const { createPlayerActionService } = require('#src/web/lib/player-actions'); const { createPlayerActionService } = require('#src/web/lib/player-actions');
const { isClientNameAvailable, withClientNameReservation } = require('#src/data/client-name-check'); const { isClientNameAvailable, withClientNameReservation } = require('#src/data/client-name-check');
const { createSessionService } = require('#src/web/lib/auth'); const { createSessionService, getRequestOrigin } = require('#src/web/lib/auth');
const { fetchAppSettings } = require('#src/data/app-settings'); const { fetchAppSettings } = require('#src/data/app-settings');
const { sendAccountEmail } = require('#src/data/mailer');
const { recordRequestAuditEvent } = require('#src/data/audit-log'); const { recordRequestAuditEvent } = require('#src/data/audit-log');
const { hasAnyPermission } = require('#src/rbac'); const { hasAnyPermission } = require('#src/rbac');
const { ensureFontLibrary } = require('#src/web/lib/media/font-library'); const { ensureFontLibrary } = require('#src/web/lib/media/font-library');
@@ -150,7 +151,10 @@ async function start() {
sessionCookieName: webConfig.sessionCookieName, sessionCookieName: webConfig.sessionCookieName,
formatDashboardDate: formatDashboardDate, formatDashboardDate: formatDashboardDate,
getAuditUserId: getAuditUserId, getAuditUserId: getAuditUserId,
getRequestOrigin: getRequestOrigin,
recordRequestAuditEvent: recordRequestAuditEvent, recordRequestAuditEvent: recordRequestAuditEvent,
sendAccountEmail: function (settings, message) { return sendAccountEmail(settings, message); },
createOneTimeToken: createOneTimeToken,
hashPassword: hashPassword, hashPassword: hashPassword,
validatePasswordStrength: validatePasswordStrength, validatePasswordStrength: validatePasswordStrength,
readArrayField: readArrayField, readArrayField: readArrayField,
@@ -234,11 +238,13 @@ async function start() {
backgroundTaskQueue: backgroundTaskQueue, backgroundTaskQueue: backgroundTaskQueue,
webBootstrap: webBootstrap, webBootstrap: webBootstrap,
notifyPlayerScreens: notifyPlayerScreens, notifyPlayerScreens: notifyPlayerScreens,
forwardPlayerCommandToDevice: playerActionService.forwardPlayerCommandToDevice,
loadCurrentUser: loadCurrentUser, loadCurrentUser: loadCurrentUser,
initializeBackgroundTasks: initializeBackgroundTasks, initializeBackgroundTasks: initializeBackgroundTasks,
captureSlideThumbnail: captureSlideThumbnail, captureSlideThumbnail: captureSlideThumbnail,
server: server, server: server,
webBaseUrl: webConfig.webInternalUrl, webBaseUrl: webConfig.webInternalUrl,
localPlayerInternalUrl: webConfig.playerInternalUrl,
dataSourceStartupRefreshStaggerMs: webConfig.dataSourceStartupRefreshStaggerMs dataSourceStartupRefreshStaggerMs: webConfig.dataSourceStartupRefreshStaggerMs
}); });
+1
View File
@@ -172,6 +172,7 @@ function registerActionHelpers(Handlebars) {
// Shared partials are registered once at startup. // Shared partials are registered once at startup.
function registerPartials(Handlebars, viewsRoot) { function registerPartials(Handlebars, viewsRoot) {
Handlebars.registerPartial('modal-shell', fs.readFileSync(path.join(viewsRoot, 'shared', 'modal-shell.hbs'), 'utf8')); Handlebars.registerPartial('modal-shell', fs.readFileSync(path.join(viewsRoot, 'shared', 'modal-shell.hbs'), 'utf8'));
Handlebars.registerPartial('media-picker-modal', fs.readFileSync(path.join(viewsRoot, 'shared', 'media-picker-modal.hbs'), 'utf8'));
Handlebars.registerPartial('table-pagination', fs.readFileSync(path.join(viewsRoot, 'shared', 'table', 'table-pagination.hbs'), 'utf8')); Handlebars.registerPartial('table-pagination', fs.readFileSync(path.join(viewsRoot, 'shared', 'table', 'table-pagination.hbs'), 'utf8'));
Handlebars.registerPartial('playlists/form', fs.readFileSync(path.join(viewsRoot, 'signage', 'playlists', 'form.hbs'), 'utf8')); Handlebars.registerPartial('playlists/form', fs.readFileSync(path.join(viewsRoot, 'signage', 'playlists', 'form.hbs'), 'utf8'));
Handlebars.registerPartial('signage/playlists/slide-row', fs.readFileSync(path.join(viewsRoot, 'signage', 'playlists', 'slide-row.hbs'), 'utf8')); Handlebars.registerPartial('signage/playlists/slide-row', fs.readFileSync(path.join(viewsRoot, 'signage', 'playlists', 'slide-row.hbs'), 'utf8'));
+1
View File
@@ -2,5 +2,6 @@
module.exports = { module.exports = {
createSessionService: require('./session').createSessionService, createSessionService: require('./session').createSessionService,
getRequestOrigin: require('./session').getRequestOrigin,
rbacData: require('./rbac-data') rbacData: require('./rbac-data')
}; };
+29 -2
View File
@@ -57,6 +57,32 @@ async function fetchRolesPage(pool, page, pageSize, searchTerm, sortKey, sortDir
return Object.assign({ roles: paged.rows }, paged); return Object.assign({ roles: paged.rows }, paged);
} }
async function fetchInvitationsPage(pool, page, pageSize, searchTerm, sortKey, sortDirection) {
const paged = await fetchPagedRows(pool, {
selectSql: `SELECT i.id, i.email, i.name, i.role_ids_json, i.created_at, i.expires_at, u.username AS created_by_username
FROM a_user_invitations i
LEFT JOIN a_users u ON u.id = i.created_by
WHERE i.used_at IS NULL AND i.expires_at > NOW()
ORDER BY i.created_at DESC`,
countSql: 'SELECT COUNT(*) AS count FROM a_user_invitations WHERE used_at IS NULL AND expires_at > NOW()',
searchColumns: ['i.email', 'i.name', 'u.username'],
searchTerm: searchTerm,
sortColumns: {
email: 'i.email',
name: 'i.name',
created: 'i.created_at',
expires: 'i.expires_at',
createdBy: 'u.username'
},
sortKey: sortKey,
sortDirection: sortDirection,
page: page,
pageSize: pageSize
});
return Object.assign({ invitations: paged.rows }, paged);
}
async function fetchRoleById(pool, roleId) { async function fetchRoleById(pool, roleId) {
const [rows] = await pool.query( const [rows] = await pool.query(
`SELECT r.id, r.role_key, r.name, r.description, r.created_at, r.modified_at, `SELECT r.id, r.role_key, r.name, r.description, r.created_at, r.modified_at,
@@ -142,7 +168,7 @@ async function fetchUsersWithRolesPage(pool, page, pageSize, searchTerm, sortKey
const whereSql = hasExcludedUserId ? 'WHERE u.id <> ?' : ''; const whereSql = hasExcludedUserId ? 'WHERE u.id <> ?' : '';
const queryArgs = hasExcludedUserId ? [excludedUserId] : []; const queryArgs = hasExcludedUserId ? [excludedUserId] : [];
const paged = await fetchPagedRows(pool, { const paged = await fetchPagedRows(pool, {
selectSql: `SELECT u.id, u.name, u.username, u.account_locked, u.created_at, u.modified_at, selectSql: `SELECT u.id, u.name, u.username, u.email, u.email_verified_at, u.account_locked, u.created_at, u.modified_at,
COALESCE(role_data.role_names, '') AS role_names, COALESCE(role_data.role_names, '') AS role_names,
COALESCE(role_data.role_ids_csv, '') AS role_ids_csv COALESCE(role_data.role_ids_csv, '') AS role_ids_csv
FROM a_users u FROM a_users u
@@ -189,7 +215,7 @@ async function fetchUsersWithRolesPage(pool, page, pageSize, searchTerm, sortKey
async function fetchUserWithRoles(pool, userId) { async function fetchUserWithRoles(pool, userId) {
const [rows] = await pool.query( const [rows] = await pool.query(
`SELECT u.id, u.name, u.username, u.account_locked, u.created_at, u.modified_at, `SELECT u.id, u.name, u.username, u.email, u.email_verified_at, u.account_locked, u.created_at, u.modified_at,
COALESCE(role_data.role_names, '') AS role_names, COALESCE(role_data.role_names, '') AS role_names,
COALESCE(role_data.role_ids_csv, '') AS role_ids_csv COALESCE(role_data.role_ids_csv, '') AS role_ids_csv
FROM a_users u FROM a_users u
@@ -299,6 +325,7 @@ module.exports = {
fetchPermissions, fetchPermissions,
fetchRoles, fetchRoles,
fetchRolesPage, fetchRolesPage,
fetchInvitationsPage,
fetchRoleById, fetchRoleById,
fetchRolePermissionKeys, fetchRolePermissionKeys,
fetchRoleUserIds, fetchRoleUserIds,
+1 -1
View File
@@ -128,7 +128,7 @@ function createSessionService(options) {
const tokenHash = hashSessionToken(token); const tokenHash = hashSessionToken(token);
const [rows] = await pool.query( const [rows] = await pool.query(
`SELECT s.user_id, u.id, u.name, u.username, u.must_change_password `SELECT s.user_id, u.id, u.name, u.username, u.email, u.email_verified_at, u.pending_email, u.must_change_password
FROM a_sessions s FROM a_sessions s
JOIN a_users u ON u.id = s.user_id JOIN a_users u ON u.id = s.user_id
WHERE s.session_hash = ? WHERE s.session_hash = ?
@@ -0,0 +1,59 @@
const { collectLocalControlUsers } = require('../../local-control-users');
const TASK = {
key: 'player-control-sync',
title: 'Player Local Control auth refresh',
category: 'player-sync',
trigger: 'scheduled recurring task, every fifteen minutes',
purpose: 'push eligible Client Control users to connected players.',
taskType: 'recurring-run',
intervalMs: 15 * 60 * 1000
};
function registerPlayerControlSyncTask(options) {
const pool = options && options.pool;
const common = options && options.common;
const backgroundTaskQueue = options && options.backgroundTaskQueue;
const forwardPlayerCommandToDevice = options && options.forwardPlayerCommandToDevice;
const localPlayerInternalUrl = String(options && options.localPlayerInternalUrl || '').trim().replace(/\/$/, '');
if (!pool || !common || !backgroundTaskQueue || typeof common.fetchPlayerRegistrations !== 'function' || typeof forwardPlayerCommandToDevice !== 'function') {
throw new Error('registerPlayerControlSyncTask requires player control sync dependencies.');
}
backgroundTaskQueue.registerRecurringTask({
key: TASK.key,
title: TASK.title,
category: TASK.category,
intervalMs: TASK.intervalMs,
metadata: {},
run: async function () {
const cachedUsers = await collectLocalControlUsers(pool);
const players = await common.fetchPlayerRegistrations(pool);
const results = await Promise.all((Array.isArray(players) ? players : []).filter(function (player) {
const playerInternalUrl = String(player && player.internal_base_url || '').trim().replace(/\/$/, '');
return !localPlayerInternalUrl || playerInternalUrl !== localPlayerInternalUrl;
}).map(async function (player) {
const deviceId = String(player && (player.identifier || player.device_id) || '').trim();
if (!deviceId) {
return { ok: false, skipped: true };
}
try {
await forwardPlayerCommandToDevice(deviceId, {
command: 'sync-local-control',
users: cachedUsers
});
return { ok: true };
} catch (_error) {
return { ok: false };
}
}));
return {
playerCount: results.length,
syncedCount: results.filter(function (result) { return result.ok; }).length
};
}
});
}
module.exports = { registerPlayerControlSyncTask };
@@ -1,42 +0,0 @@
const TASK = {
key: 'unused-upload-sweep',
title: 'Unused upload sweep',
category: 'cleanup',
trigger: 'recurring scheduled task, daily',
purpose: 'remove uploaded media files that are no longer referenced.',
taskType: 'recurring-run',
intervalMs: 24 * 60 * 60 * 1000
};
function registerUnusedUploadSweepTask(options) {
const backgroundTaskQueue = options && options.backgroundTaskQueue;
const uploadSyncService = options && options.uploadSyncService;
const collectUploadPathsFromDirectory = uploadSyncService && uploadSyncService.collectUploadPathsFromDirectory;
const removeUnusedUploadFiles = uploadSyncService && uploadSyncService.removeUnusedUploadFiles;
const pool = options && options.pool;
const mediaDir = String(options && options.mediaDir || '').trim();
if (!backgroundTaskQueue || typeof collectUploadPathsFromDirectory !== 'function' || typeof removeUnusedUploadFiles !== 'function' || !pool || !mediaDir) {
throw new Error('registerUnusedUploadSweepTask requires the unused upload sweep dependencies.');
}
backgroundTaskQueue.registerRecurringTask({
key: TASK.key,
title: TASK.title,
category: TASK.category,
intervalMs: TASK.intervalMs,
metadata: {
mediaDir: mediaDir
},
run: async function () {
const uploadPaths = await collectUploadPathsFromDirectory(mediaDir);
if (!uploadPaths.length) {
return;
}
await removeUnusedUploadFiles(pool, mediaDir, uploadPaths);
}
});
}
module.exports = { registerUnusedUploadSweepTask };
+26
View File
@@ -0,0 +1,26 @@
const crypto = require('crypto');
async function collectLocalControlUsers(pool) {
const [rows] = await pool.query(
`SELECT DISTINCT u.username, u.password_hash, u.password_salt
FROM a_users u
JOIN a_user_roles ur ON ur.user_id = u.id
JOIN a_role_permissions rp ON rp.role_id = ur.role_id
JOIN a_permissions p ON p.id = rp.permission_id
WHERE u.account_locked = 0
AND u.must_change_password = 0
AND p.permission_key = 'clients.allow'
ORDER BY u.username ASC`
);
return (rows || []).map(function (user) {
return {
username_hash: crypto.createHash('sha256').update(String(user && user.username || '').trim()).digest('hex'),
password_hash: String(user && user.password_hash || '').trim(),
password_salt: String(user && user.password_salt || '').trim()
};
}).filter(function (user) {
return Boolean(user.username_hash && user.password_hash && user.password_salt);
});
}
module.exports = { collectLocalControlUsers };
+178
View File
@@ -0,0 +1,178 @@
// Data access helpers for the shared media library.
const fs = require('fs');
const path = require('path');
const MEDIA_MIME_TYPES = {
'.gif': 'image/gif',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.avi': 'video/x-msvideo',
'.mov': 'video/quicktime',
'.mp4': 'video/mp4',
'.mpeg': 'video/mpeg',
'.webm': 'video/webm'
};
function normalizeMediaPath(value) {
const mediaPath = String(value || '').trim();
return mediaPath.startsWith('/media/') ? mediaPath : null;
}
async function registerMediaAsset(pool, file, mediaPath, userId, options) {
const normalizedPath = normalizeMediaPath(mediaPath);
if (!pool || !file || !normalizedPath) {
return null;
}
await pool.query(
`INSERT INTO c_media_assets
(media_path, original_name, media_type, mime_type, file_size, is_published, created_by, modified_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
${options && options.preserveOriginalName ? 'original_name = original_name,' : 'original_name = VALUES(original_name),' }
media_type = VALUES(media_type),
mime_type = VALUES(mime_type),
file_size = VALUES(file_size),
${options && options.preservePublication ? 'is_published = is_published,' : 'is_published = VALUES(is_published),' }
modified_by = VALUES(modified_by)`,
[
normalizedPath,
String(file.originalname || file.filename || 'media').slice(0, 255),
String(file.mediaType || '').trim() || 'unknown',
String(file.mimetype || '').trim() || 'application/octet-stream',
Number(file.size) || 0,
options && options.published === false ? 0 : 1,
userId || null,
userId || null
]
);
return normalizedPath;
}
async function registerMediaAssets(pool, files, getMediaPath, getMediaType, userId, options) {
const registered = [];
const list = Array.isArray(files) ? files : [];
for (let index = 0; index < list.length; index += 1) {
const file = list[index];
const mediaPath = typeof getMediaPath === 'function' ? getMediaPath(file) : null;
if (!mediaPath) {
continue;
}
const enrichedFile = Object.assign({}, file, {
mediaType: typeof getMediaType === 'function' ? getMediaType(file) : 'unknown'
});
registered.push(await registerMediaAsset(pool, enrichedFile, mediaPath, userId, options));
}
return registered.filter(Boolean);
}
async function fetchMediaAssets(pool) {
const [rows] = await pool.query(
`SELECT id, media_path, original_name, media_type, mime_type, file_size, created_at
FROM c_media_assets
WHERE is_published = 1
ORDER BY created_at DESC, id DESC`
);
return rows || [];
}
async function syncMediaAssetsFromDirectory(pool, uploadDir, userId) {
const directory = String(uploadDir || '').trim();
if (!pool || !directory) {
return 0;
}
let entries;
try {
entries = await fs.promises.readdir(directory, { withFileTypes: true });
} catch (error) {
if (error && error.code === 'ENOENT') {
return 0;
}
throw error;
}
let registeredCount = 0;
for (const entry of entries) {
if (!entry || !entry.isFile()) {
continue;
}
const originalName = String(entry.name || '').trim();
const mimeType = MEDIA_MIME_TYPES[path.extname(originalName).toLowerCase()];
if (!mimeType) {
continue;
}
const filePath = path.join(directory, originalName);
const stats = await fs.promises.stat(filePath);
const result = await registerMediaAsset(pool, {
originalname: originalName,
mimetype: mimeType,
size: stats.size,
mediaType: mimeType.startsWith('video/') ? 'video' : 'image'
}, '/media/uploads/' + originalName, userId, { preserveOriginalName: true, preservePublication: true });
if (result) {
registeredCount += 1;
}
}
return registeredCount;
}
async function countMediaAssetReferences(pool, mediaPath) {
const normalizedPath = normalizeMediaPath(mediaPath);
if (!normalizedPath) {
return 0;
}
const [slideRows] = await pool.query(
`SELECT COUNT(*) AS ref_count
FROM c_slides
WHERE LOCATE(?, COALESCE(content_json, '')) > 0`,
[normalizedPath]
);
const [templateRows] = await pool.query(
'SELECT COUNT(*) AS ref_count FROM c_templates WHERE background_image_path = ?',
[normalizedPath]
);
return Number(slideRows[0] && slideRows[0].ref_count || 0) + Number(templateRows[0] && templateRows[0].ref_count || 0);
}
async function publishMediaAssets(pool, mediaPaths) {
const paths = Array.from(new Set((Array.isArray(mediaPaths) ? mediaPaths : []).map(normalizeMediaPath).filter(Boolean)));
for (let index = 0; index < paths.length; index += 1) {
await pool.query('UPDATE c_media_assets SET is_published = 1 WHERE media_path = ?', [paths[index]]);
}
}
async function removePendingMediaAssets(pool, uploadDir, mediaPaths) {
const paths = Array.from(new Set((Array.isArray(mediaPaths) ? mediaPaths : []).map(normalizeMediaPath).filter(Boolean)));
for (let index = 0; index < paths.length; index += 1) {
const mediaPath = paths[index];
const [rows] = await pool.query('SELECT id FROM c_media_assets WHERE media_path = ? AND is_published = 0 LIMIT 1', [mediaPath]);
const asset = rows && rows[0];
if (!asset || await countMediaAssetReferences(pool, mediaPath) > 0) {
continue;
}
await pool.query('DELETE FROM c_media_assets WHERE id = ?', [asset.id]);
const filePath = path.join(path.dirname(uploadDir), mediaPath.replace(/^\/media\//, ''));
await fs.promises.unlink(filePath).catch(function (error) {
if (error && error.code !== 'ENOENT') {
throw error;
}
});
}
}
module.exports = {
normalizeMediaPath,
registerMediaAsset,
registerMediaAssets,
fetchMediaAssets,
syncMediaAssetsFromDirectory,
countMediaAssetReferences,
publishMediaAssets,
removePendingMediaAssets
};
+3
View File
@@ -184,6 +184,9 @@ function substitutePlaceholders(html, regionContent, options) {
const resolved = typeof placeholderUtils.resolvePlaceholderExpression === 'function' const resolved = typeof placeholderUtils.resolvePlaceholderExpression === 'function'
? placeholderUtils.resolvePlaceholderExpression(item, weatherExpression, { timeZone: item.timezone }) ? placeholderUtils.resolvePlaceholderExpression(item, weatherExpression, { timeZone: item.timezone })
: resolvePlaceholderPath(item, expression); : resolvePlaceholderPath(item, expression);
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(expression)) {
return placeholderUtils.renderProgressPlaceholder(item, expression);
}
if (type === 'weather' && /(?:^|\.)weather_code\.\d+\.icon(?:\(|$)|^current\.weather_code\.icon/.test(weatherExpression)) { if (type === 'weather' && /(?:^|\.)weather_code\.\d+\.icon(?:\(|$)|^current\.weather_code\.icon/.test(weatherExpression)) {
const codeExpression = weatherExpression.replace(/\.icon(?:\(.*\))?$/, ''); const codeExpression = weatherExpression.replace(/\.icon(?:\(.*\))?$/, '');
const iconSize = String(expression).match(/\.icon\(\s*(\d+)(?:\s*,\s*(\d+))?\s*\)$/); const iconSize = String(expression).match(/\.icon\(\s*(\d+)(?:\s*,\s*(\d+))?\s*\)$/);
+35 -27
View File
@@ -253,10 +253,18 @@ function createUploadSyncService(options) {
function normalizeUploadReference(uploadPath) { function normalizeUploadReference(uploadPath) {
const value = String(uploadPath || '').trim(); const value = String(uploadPath || '').trim();
if (!value || !value.startsWith('/media/')) { if (!value) {
return null;
}
if (value.startsWith('/media/')) {
return value;
}
try {
const parsed = new URL(value);
return parsed.pathname.startsWith('/media/') ? parsed.pathname : null;
} catch (_error) {
return null; return null;
} }
return value;
} }
function getUploadRelativePath(uploadPath) { function getUploadRelativePath(uploadPath) {
@@ -313,6 +321,13 @@ function createUploadSyncService(options) {
if (reference) { if (reference) {
refs.add(reference); refs.add(reference);
} }
const embeddedReferences = current.match(/\/media\/[^"'\s<>)]+/g) || [];
embeddedReferences.forEach(function (embeddedReference) {
const normalizedReference = normalizeUploadReference(embeddedReference);
if (normalizedReference) {
refs.add(normalizedReference);
}
});
} }
} }
return refs; return refs;
@@ -364,32 +379,21 @@ function createUploadSyncService(options) {
return Number(slideRows[0].ref_count || 0) + Number(thumbnailRows[0].ref_count || 0) + Number(templateRows[0].ref_count || 0); return Number(slideRows[0].ref_count || 0) + Number(thumbnailRows[0].ref_count || 0) + Number(templateRows[0].ref_count || 0);
} }
async function removeUnusedUploadFiles(pool, uploadDir, uploadPaths) { async function uploadFileExists(uploadDir, uploadPath) {
const uniquePaths = Array.from(new Set((uploadPaths || []).map(normalizeUploadReference).filter(Boolean))); const filePath = resolveUploadFilePath(uploadDir, uploadPath);
for (let i = 0; i < uniquePaths.length; i += 1) { if (!filePath) {
const uploadPath = uniquePaths[i]; return false;
const referenceCount = await countUploadReferences(pool, uploadPath);
if (referenceCount > 0) {
continue;
}
const filePath = resolveUploadFilePath(uploadDir, uploadPath);
if (String(uploadPath || '').startsWith('/media/player-cache/')) {
continue;
}
try {
await fs.promises.unlink(filePath);
} catch (error) {
if (error && error.code !== 'ENOENT') {
console.warn('Unable to remove unused upload file:', filePath, error);
}
}
queuePlayerUploadSync({
type: 'delete',
uploadPath: uploadPath,
uploadDir: uploadDir
});
} }
try {
await fs.promises.access(filePath, fs.constants.F_OK);
return true;
} catch (_error) {
return false;
}
}
async function removeUnusedUploadFiles(pool, uploadDir, uploadPaths) {
return;
} }
async function collectUploadPathsFromDirectory(uploadDir) { async function collectUploadPathsFromDirectory(uploadDir) {
@@ -981,6 +985,10 @@ function createUploadSyncService(options) {
continue; continue;
} }
if (isLocalLikeBaseUrl(taskPayload.playerInternalBaseUrl) && await uploadFileExists(operation.localUploadDir, removedUploadRef)) {
continue;
}
const deleted = await removeUploadFileFromPlayer(removedUploadRef, operation.localUploadDir, taskPayload.playerInternalBaseUrl, taskPayload.playerIdentifier); const deleted = await removeUploadFileFromPlayer(removedUploadRef, operation.localUploadDir, taskPayload.playerInternalBaseUrl, taskPayload.playerIdentifier);
if (!deleted) { if (!deleted) {
queuePlayerUploadSync({ queuePlayerUploadSync({
+4
View File
@@ -9,6 +9,8 @@ async function initializeWebServer(options) {
const loadCurrentUser = options && options.loadCurrentUser; const loadCurrentUser = options && options.loadCurrentUser;
const initializeBackgroundTasks = options && options.initializeBackgroundTasks; const initializeBackgroundTasks = options && options.initializeBackgroundTasks;
const captureSlideThumbnail = options && options.captureSlideThumbnail; const captureSlideThumbnail = options && options.captureSlideThumbnail;
const forwardPlayerCommandToDevice = options && options.forwardPlayerCommandToDevice;
const localPlayerInternalUrl = options && options.localPlayerInternalUrl;
const dataSourceStartupRefreshStaggerMs = Math.max(100, Number(options && options.dataSourceStartupRefreshStaggerMs || 250)); const dataSourceStartupRefreshStaggerMs = Math.max(100, Number(options && options.dataSourceStartupRefreshStaggerMs || 250));
const server = options && options.server; const server = options && options.server;
@@ -25,9 +27,11 @@ async function initializeWebServer(options) {
common: common, common: common,
backgroundTaskQueue: backgroundTaskQueue, backgroundTaskQueue: backgroundTaskQueue,
notifyPlayerScreens: options && options.notifyPlayerScreens ? options.notifyPlayerScreens : null, notifyPlayerScreens: options && options.notifyPlayerScreens ? options.notifyPlayerScreens : null,
forwardPlayerCommandToDevice: forwardPlayerCommandToDevice,
uploadSyncService: webBootstrap.uploadSyncService, uploadSyncService: webBootstrap.uploadSyncService,
captureSlideThumbnail: captureSlideThumbnail, captureSlideThumbnail: captureSlideThumbnail,
mediaDir: mediaDir, mediaDir: mediaDir,
localPlayerInternalUrl: localPlayerInternalUrl,
webBaseUrl: options && options.webBaseUrl ? options.webBaseUrl : null, webBaseUrl: options && options.webBaseUrl ? options.webBaseUrl : null,
dataSourceStartupRefreshStaggerMs: dataSourceStartupRefreshStaggerMs dataSourceStartupRefreshStaggerMs: dataSourceStartupRefreshStaggerMs
}); });
+1 -1
View File
@@ -29,7 +29,7 @@ module.exports = function registerMiddleware(app, deps) {
}); });
app.use(function (req, res, next) { app.use(function (req, res, next) {
if (req.path === '/' || req.path === '/login' || req.path === '/logout' || req.path === '/slides/popup-preview' || req.path.indexOf('/api/internal/slide-thumbnails/') === 0 || req.path === '/api/internal/sync/player-media' || req.path === '/api/internal/sync/player-font') { if (req.path === '/' || req.path === '/login' || req.path === '/logout' || req.path === '/forgot-password' || req.path === '/reset-password' || req.path === '/verify-email' || req.path === '/slides/popup-preview' || req.path.indexOf('/api/internal/slide-thumbnails/') === 0 || req.path === '/api/internal/sync/player-media' || req.path === '/api/internal/sync/player-font' || req.path === '/api/internal/sync/player-control') {
return next(); return next();
} }
+8
View File
@@ -8,11 +8,18 @@ function routePath(...segments) {
module.exports = { module.exports = {
renderLoginPage: require(routePath('auth', 'login')), renderLoginPage: require(routePath('auth', 'login')),
renderForgotPasswordPage: require(routePath('auth', 'forgot-password')),
renderResetPasswordPage: require(routePath('auth', 'reset-password')),
renderAcceptInvitePage: require(routePath('auth', 'accept-invite')),
renderEmailVerifiedPage: require(routePath('auth', 'email-verified')),
renderEmailVerificationErrorPage: require(routePath('auth', 'email-verification-error')),
renderAccountPage: require(routePath('account', 'password')), renderAccountPage: require(routePath('account', 'password')),
renderSettingsPage: require(routePath('settings', 'index')), renderSettingsPage: require(routePath('settings', 'index')),
renderAboutPage: require(routePath('settings', 'about', 'index')), renderAboutPage: require(routePath('settings', 'about', 'index')),
renderUsersPage: require(routePath('settings', 'users', 'list')), renderUsersPage: require(routePath('settings', 'users', 'list')),
renderInvitationsPage: require(routePath('settings', 'invitations', 'list')),
renderUsersAddPage: require(routePath('settings', 'users', 'add')), renderUsersAddPage: require(routePath('settings', 'users', 'add')),
renderUsersInvitePage: require(routePath('settings', 'users', 'invite')),
renderUsersEditPage: require(routePath('settings', 'users', 'edit')), renderUsersEditPage: require(routePath('settings', 'users', 'edit')),
renderDashboardPage: require(routePath('signage', 'dashboard', 'index')), renderDashboardPage: require(routePath('signage', 'dashboard', 'index')),
renderConnectedClientsPage: require(routePath('signage', 'clients', 'list')), renderConnectedClientsPage: require(routePath('signage', 'clients', 'list')),
@@ -48,6 +55,7 @@ module.exports = {
renderCanvasSizeAddPage: require(routePath('signage', 'canvas-sizes', 'add')), renderCanvasSizeAddPage: require(routePath('signage', 'canvas-sizes', 'add')),
renderCanvasSizeEditPage: require(routePath('signage', 'canvas-sizes', 'edit')), renderCanvasSizeEditPage: require(routePath('signage', 'canvas-sizes', 'edit')),
renderFontsPage: require(routePath('settings', 'fonts', 'list')), renderFontsPage: require(routePath('settings', 'fonts', 'list')),
renderMediaLibraryPage: require(routePath('settings', 'media-library', 'list')),
renderBackgroundTasksPage: require(routePath('settings', 'background-tasks-page')).renderBackgroundTasksPage, renderBackgroundTasksPage: require(routePath('settings', 'background-tasks-page')).renderBackgroundTasksPage,
renderBackgroundTasksScheduledPage: require(routePath('settings', 'background-tasks-page')).renderBackgroundTasksScheduledPage, renderBackgroundTasksScheduledPage: require(routePath('settings', 'background-tasks-page')).renderBackgroundTasksScheduledPage,
renderErrorPage: require('./error'), renderErrorPage: require('./error'),
+1 -1
View File
@@ -1,5 +1,5 @@
@charset "UTF-8";/*! @charset "UTF-8";/*!
* AdminLTE v4.8.5 Extended color palette * AdminLTE v4.9.1 Extended color palette
* Opt-in. Nothing here is in adminlte.css: load this sheet after it and you * Opt-in. Nothing here is in adminlte.css: load this sheet after it and you
* get fourteen additional colours (orange, amber, olive, teal, sky, indigo, * get fourteen additional colours (orange, amber, olive, teal, sky, indigo,
* violet, fuchsia, pink, navy, steel, slate, graphite, midnight) as `--bs-*` * violet, fuchsia, pink, navy, steel, slate, graphite, midnight) as `--bs-*`
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,5 +1,5 @@
/*! /*!
* AdminLTE v4.3.1 (https://adminlte.io) * AdminLTE v4.9.1 (https://adminlte.io)
* Copyright 2014-2026 Colorlib <https://colorlib.com> * Copyright 2014-2026 Colorlib <https://colorlib.com>
* Licensed under MIT (https://github.com/ColorlibHQ/AdminLTE/blob/master/LICENSE) * Licensed under MIT (https://github.com/ColorlibHQ/AdminLTE/blob/master/LICENSE)
*/ */
File diff suppressed because it is too large Load Diff
+56
View File
@@ -0,0 +1,56 @@
(function () {
var currentPasswordInput = document.querySelector('[data-account-current-password]');
var profileFormInput = document.querySelector('[data-account-profile-current-password]');
var passwordFormInput = document.querySelector('[data-account-password-current-password]');
var profileForm = profileFormInput && profileFormInput.form;
var passwordForm = passwordFormInput && passwordFormInput.form;
if (!currentPasswordInput || !profileFormInput || !passwordFormInput || !profileForm || !passwordForm) {
return;
}
function syncCurrentPassword() {
profileFormInput.value = currentPasswordInput.value;
passwordFormInput.value = currentPasswordInput.value;
}
function clearCurrentPassword() {
currentPasswordInput.value = '';
currentPasswordInput.setCustomValidity('');
currentPasswordInput.removeAttribute('required');
profileFormInput.value = '';
passwordFormInput.value = '';
passwordForm.querySelectorAll('input[type="password"]').forEach(function (input) {
input.value = '';
input.setCustomValidity('');
});
profileForm.classList.remove('was-validated');
passwordForm.classList.remove('was-validated');
}
currentPasswordInput.addEventListener('input', syncCurrentPassword);
currentPasswordInput.addEventListener('input', function () {
currentPasswordInput.setCustomValidity('');
});
document.addEventListener('submit', function (event) {
if (event.target !== profileForm && event.target !== passwordForm) {
return;
}
if (!currentPasswordInput.value) {
event.preventDefault();
event.stopImmediatePropagation();
currentPasswordInput.setCustomValidity('Current password is required.');
currentPasswordInput.reportValidity();
return;
}
currentPasswordInput.setCustomValidity('');
syncCurrentPassword();
}, true);
passwordForm.addEventListener('submit', syncCurrentPassword);
document.addEventListener('web-async-save:success', function (event) {
if (event.detail && event.detail.form !== profileForm && event.detail.form !== passwordForm) {
return;
}
clearCurrentPassword();
});
})();
+85 -7
View File
@@ -72,9 +72,13 @@
var allBlackout = hasClients && clients.every(function (client) { var allBlackout = hasClients && clients.every(function (client) {
return Boolean(client && client.blackout); return Boolean(client && client.blackout);
}); });
var isClientsMobile = Boolean(document.querySelector('.clients-screen-command-card'));
var useShortMobileLabels = isClientsMobile && window.innerWidth < 768;
if (action === 'pause') { if (action === 'pause') {
var pauseLabel = allPaused ? 'Resume ' + (isAllScreens ? 'all clients' : 'screen') : 'Pause ' + (isAllScreens ? 'all clients' : 'screen'); var pauseLabel = useShortMobileLabels
? (allPaused ? 'Resume' : 'Pause')
: (allPaused ? 'Resume ' + (isAllScreens ? 'all clients' : 'screen') : 'Pause ' + (isAllScreens ? 'all clients' : 'screen'));
var pauseConfirm = allPaused ? 'Resume ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?' : 'Pause ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?'; var pauseConfirm = allPaused ? 'Resume ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?' : 'Pause ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?';
var pauseIcon = allPaused ? 'bi-play-fill' : 'bi-pause-fill'; var pauseIcon = allPaused ? 'bi-play-fill' : 'bi-pause-fill';
button.innerHTML = '<i class="bi ' + pauseIcon + ' me-1" aria-hidden="true"></i>' + escapeHtml(pauseLabel); button.innerHTML = '<i class="bi ' + pauseIcon + ' me-1" aria-hidden="true"></i>' + escapeHtml(pauseLabel);
@@ -92,7 +96,9 @@
} }
if (action === 'blackout') { if (action === 'blackout') {
var blackoutLabel = allBlackout ? 'Restore ' + (isAllScreens ? 'all clients' : 'screen') : 'Blackout ' + (isAllScreens ? 'all clients' : 'screen'); var blackoutLabel = useShortMobileLabels
? (allBlackout ? 'Restore' : 'Blackout')
: (allBlackout ? 'Restore ' + (isAllScreens ? 'all clients' : 'screen') : 'Blackout ' + (isAllScreens ? 'all clients' : 'screen'));
var blackoutConfirm = allBlackout ? 'Restore ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?' : 'Blackout ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?'; var blackoutConfirm = allBlackout ? 'Restore ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?' : 'Blackout ' + (isAllScreens ? 'all connected clients' : selectedLabel) + '?';
var blackoutIcon = allBlackout ? 'bi-eye' : 'bi-eye-slash'; var blackoutIcon = allBlackout ? 'bi-eye' : 'bi-eye-slash';
button.innerHTML = '<i class="bi ' + blackoutIcon + ' me-1" aria-hidden="true"></i>' + escapeHtml(blackoutLabel); button.innerHTML = '<i class="bi ' + blackoutIcon + ' me-1" aria-hidden="true"></i>' + escapeHtml(blackoutLabel);
@@ -147,6 +153,9 @@
} }
if (button) { if (button) {
if (Boolean(document.querySelector('.clients-screen-command-card')) && window.innerWidth < 768) {
button.innerHTML = '<i class="bi bi-arrow-repeat me-1" aria-hidden="true"></i>Reload';
}
button.setAttribute('aria-label', selectedName ? selectedName : 'Selected screen group'); button.setAttribute('aria-label', selectedName ? selectedName : 'Selected screen group');
} }
}); });
@@ -372,7 +381,7 @@
var connectionId = String(row.getAttribute('data-client-client-id') || row.getAttribute('data-client-id') || '').trim(); var connectionId = String(row.getAttribute('data-client-client-id') || row.getAttribute('data-client-id') || '').trim();
var clientId = String(row.getAttribute('data-client-client-id') || '').trim(); var clientId = String(row.getAttribute('data-client-client-id') || '').trim();
var playerBaseUrl = String(row.getAttribute('data-client-player-base-url') || '').trim(); var playerBaseUrl = String(row.getAttribute('data-client-player-base-url') || '').trim();
var clientNameCell = row.querySelector('td[data-label="Client"] > div'); var clientNameCell = row.querySelector('td[data-label="Client"] > div, [data-mobile-client-name]');
var clientName = String(clientNameCell && clientNameCell.textContent || '').trim(); var clientName = String(clientNameCell && clientNameCell.textContent || '').trim();
var options = Array.prototype.slice.call(elements.targetSelect.options || []); var options = Array.prototype.slice.call(elements.targetSelect.options || []);
@@ -826,7 +835,7 @@
if (typeof elements.modal.addEventListener === 'function') { if (typeof elements.modal.addEventListener === 'function') {
elements.modal.addEventListener('show.bs.modal', function (event) { elements.modal.addEventListener('show.bs.modal', function (event) {
var trigger = event && event.relatedTarget ? event.relatedTarget : null; var trigger = event && event.relatedTarget ? event.relatedTarget : null;
var row = trigger && trigger.closest ? trigger.closest('tr[data-client-key]') : null; var row = trigger && trigger.closest ? trigger.closest('tr[data-client-key], article[data-mobile-client-key]') : null;
if (row) { if (row) {
updateClientMoveModalFromRow(row); updateClientMoveModalFromRow(row);
} }
@@ -843,7 +852,7 @@
event.preventDefault(); event.preventDefault();
} }
var row = moveButton.closest ? moveButton.closest('tr[data-client-key]') : null; var row = moveButton.closest ? moveButton.closest('tr[data-client-key], article[data-mobile-client-key]') : null;
if (!row) { if (!row) {
return; return;
} }
@@ -1038,6 +1047,60 @@
blackoutButton.setAttribute('aria-label', label); blackoutButton.setAttribute('aria-label', label);
} }
function updateMobileClientCards(state) {
document.querySelectorAll('[data-mobile-client-id]').forEach(function (card) {
var id = String(card.getAttribute('data-mobile-client-id') || '').trim();
var clientId = String(card.getAttribute('data-mobile-client-client-id') || '').trim();
var client = (state.clients || []).find(function (candidate) {
return String(candidate.id || '').trim() === id || String(candidate.clientId || '').trim() === clientId;
});
if (!client) {
return;
}
var paused = Boolean(client.paused);
var blackout = Boolean(client.blackout);
var badge = card.querySelector('.badge');
var heading = card.querySelector('h4');
var details = card.querySelectorAll('.clients-mobile-client-details strong');
var pauseButton = card.querySelector('button[type="submit"].btn-info');
var blackoutButton = card.querySelector('button[type="submit"].btn-secondary, button[type="submit"].btn-success');
card.setAttribute('data-client-screen-slug', client.screen_slug || '');
card.setAttribute('data-client-client-id', client.clientId || client.id || '');
card.setAttribute('data-client-player-base-url', client.player_url || '');
card.classList.toggle('card-warning', paused);
card.classList.toggle('card-primary', !paused);
if (badge) {
badge.className = 'badge ' + (blackout ? 'text-bg-secondary' : paused ? 'text-bg-warning' : 'text-bg-success');
badge.textContent = blackout ? 'Blackout' : paused ? 'Paused' : 'Live';
}
if (heading) {
heading.textContent = client.client_name || 'Unknown';
}
if (details[0]) {
details[0].textContent = client.screen_name || client.screen_slug || 'Unknown';
}
if (details[1]) {
details[1].textContent = client.currentSlideTitle || 'No slide currently showing';
}
if (pauseButton) {
pauseButton.innerHTML = '<i class="bi ' + (paused ? 'bi-play-fill' : 'bi-pause-fill') + ' me-1" aria-hidden="true"></i>' + (paused ? 'Resume' : 'Pause');
}
if (blackoutButton) {
blackoutButton.innerHTML = '<i class="bi ' + (blackout ? 'bi-eye' : 'bi-eye-slash') + ' me-1" aria-hidden="true"></i>' + (blackout ? 'Restore' : 'Blackout');
blackoutButton.className = 'btn btn-sm ' + (blackout ? 'btn-success' : 'btn-secondary') + ' w-100';
}
card.querySelectorAll('form').forEach(function (form) {
var connectionInput = form.querySelector('input[name="connectionId"]');
var baseUrlInput = form.querySelector('input[name="playerBaseUrl"]');
if (connectionInput) connectionInput.value = client.clientId || client.id || '';
if (baseUrlInput) baseUrlInput.value = client.player_url || '';
form.action = '/clients/' + encodeURIComponent(client.screen_slug || '') + '/commands';
var blackoutInput = form.querySelector('input[name="blackout"]');
if (blackoutInput) blackoutInput.value = blackout ? 'false' : 'true';
});
});
}
function handleDashboardState(state) { function handleDashboardState(state) {
if (!state) { if (!state) {
return; return;
@@ -1047,6 +1110,7 @@
updateStats(state); updateStats(state);
updateScreenGrid(state); updateScreenGrid(state);
updateClientTable(state); updateClientTable(state);
updateMobileClientCards(state);
updateKioskLauncherModal(state); updateKioskLauncherModal(state);
updateDashboardQuickActions(state); updateDashboardQuickActions(state);
updateScreenCommandControls(); updateScreenCommandControls();
@@ -1142,10 +1206,24 @@
return; return;
} }
document.querySelectorAll('article[data-mobile-client-key] .clients-mobile-client-actions').forEach(function (actions) {
if (actions.querySelector('button[data-action="move-screen"]')) {
return;
}
var button = document.createElement('button');
button.type = 'button';
button.className = 'btn btn-sm btn-danger';
button.setAttribute('data-action', 'move-screen');
button.setAttribute('aria-label', 'Change screen');
button.setAttribute('title', 'Change screen');
button.innerHTML = '<i class="bi bi-display" aria-hidden="true"></i>';
actions.insertBefore(button, actions.children[1] || null);
});
if (typeof elements.modal.addEventListener === 'function') { if (typeof elements.modal.addEventListener === 'function') {
elements.modal.addEventListener('show.bs.modal', function (event) { elements.modal.addEventListener('show.bs.modal', function (event) {
var trigger = event && event.relatedTarget ? event.relatedTarget : null; var trigger = event && event.relatedTarget ? event.relatedTarget : null;
var row = trigger && trigger.closest ? trigger.closest('tr[data-client-key]') : null; var row = trigger && trigger.closest ? trigger.closest('tr[data-client-key], article[data-mobile-client-key]') : null;
if (row) { if (row) {
updateClientMoveModalFromRow(row); updateClientMoveModalFromRow(row);
} }
@@ -1162,7 +1240,7 @@
event.preventDefault(); event.preventDefault();
} }
var row = moveButton.closest ? moveButton.closest('tr[data-client-key]') : null; var row = moveButton.closest ? moveButton.closest('tr[data-client-key], article[data-mobile-client-key]') : null;
if (!row) { if (!row) {
return; return;
} }
@@ -7,6 +7,7 @@
} }
var methodSelect = form.querySelector('[data-api-source-auth-method]'); var methodSelect = form.querySelector('[data-api-source-auth-method]');
var authCard = form.querySelector('[data-api-source-auth-card]');
var authDetailsSection = form.querySelector('[data-api-source-auth-details-section]'); var authDetailsSection = form.querySelector('[data-api-source-auth-details-section]');
var panels = Array.prototype.slice.call(form.querySelectorAll('[data-api-source-auth-panel]')); var panels = Array.prototype.slice.call(form.querySelectorAll('[data-api-source-auth-panel]'));
var bearerTokenInput = form.querySelector('[data-api-source-bearer-token-input]'); var bearerTokenInput = form.querySelector('[data-api-source-bearer-token-input]');
@@ -36,10 +37,20 @@
bearerTokenInput.focus(); bearerTokenInput.focus();
} }
function updatePanels() { function updatePanels(shouldExpandAuth) {
var method = String(methodSelect && methodSelect.value || 'none').trim(); var method = String(methodSelect && methodSelect.value || 'none').trim();
var hasAuth = method !== 'none'; var hasAuth = method !== 'none';
if (authCard) {
authCard.hidden = !hasAuth;
if (shouldExpandAuth && hasAuth && authCard.classList.contains('collapsed-card')) {
var collapseButton = authCard.querySelector('[data-lte-toggle="card-collapse"]');
if (collapseButton) {
collapseButton.click();
}
}
}
if (authDetailsSection) { if (authDetailsSection) {
authDetailsSection.hidden = !hasAuth; authDetailsSection.hidden = !hasAuth;
} }
@@ -60,7 +71,9 @@
} }
if (methodSelect) { if (methodSelect) {
methodSelect.addEventListener('change', updatePanels); methodSelect.addEventListener('change', function () {
updatePanels(true);
});
} }
if (requestMethodSelect) { if (requestMethodSelect) {
@@ -72,6 +85,6 @@
updateBearerTokenToggle(); updateBearerTokenToggle();
} }
updatePanels(); updatePanels(false);
updateRequestBodyVisibility(); updateRequestBodyVisibility();
}()); }());
+289
View File
@@ -0,0 +1,289 @@
// Shared media library picker for editor forms.
(function () {
var modal = document.getElementById('media-picker-modal');
if (!modal) {
return;
}
var activeButton = null;
var items = Array.prototype.slice.call(modal.querySelectorAll('[data-media-picker-item]'));
var grid = modal.querySelector('[data-media-picker-grid]');
var search = modal.querySelector('[data-media-picker-search]');
var sort = modal.querySelector('[data-media-picker-sort]');
var noResults = modal.querySelector('[data-media-picker-no-results]');
var loadMoreWrap = modal.querySelector('[data-media-picker-load-more-wrap]');
var loadMoreButton = modal.querySelector('[data-media-picker-load-more]');
var confirmButton = modal.querySelector('[data-media-picker-confirm]');
var cancelButton = modal.querySelector('[data-media-picker-cancel]');
var uploadButton = modal.querySelector('[data-media-picker-upload]');
var currentPath = '';
var pendingPath = '';
var pendingType = '';
var visibleRowLimit = 4;
var loadedAssets = [];
var mediaOffset = 0;
var mediaHasMore = false;
var refreshSequence = 0;
function getColumnsPerRow() {
return window.innerWidth >= 992 ? 4 : window.innerWidth >= 768 ? 3 : 2;
}
function renderItems(assets) {
if (!grid) {
return;
}
grid.innerHTML = (Array.isArray(assets) ? assets : []).map(function (asset) {
var type = String(asset.media_type || '');
var path = escapeHtml(asset.media_path);
var name = escapeHtml(asset.original_name);
var createdAt = escapeHtml(asset.created_at);
var preview = type === 'video'
? '<video src="' + path + '" muted playsinline preload="metadata"></video>'
: '<img src="' + path + '" alt="" loading="lazy" />';
return '<div class="col-6 col-md-4 col-lg-3" data-media-picker-item data-media-type="' + escapeHtml(type) + '" data-media-name="' + name + '" data-media-created-at="' + createdAt + '">' +
'<button type="button" class="media-picker-item w-100 text-start" data-media-picker-path="' + path + '" data-media-picker-type="' + escapeHtml(type) + '">' +
'<span class="media-picker-item-preview">' + preview + '</span>' +
'<span class="media-picker-item-name text-truncate d-block">' + name + '</span>' +
'<span class="media-picker-item-statuses"><span class="media-picker-item-current" data-media-picker-current hidden><i class="bi bi-check-circle me-1" aria-hidden="true"></i>Current</span><span class="media-picker-item-selected" data-media-picker-selected hidden><i class="bi bi-check-circle-fill me-1" aria-hidden="true"></i>Selected</span></span>' +
'</button></div>';
}).join('');
items = Array.prototype.slice.call(modal.querySelectorAll('[data-media-picker-item]'));
}
function getQueryParams(offset, limit) {
var params = new URLSearchParams();
var type = activeButton ? activeButton.getAttribute('data-media-picker-type') || 'image' : 'image';
params.set('offset', String(offset));
params.set('limit', String(limit));
params.set('search', String(search && search.value || '').trim());
params.set('type', type);
params.set('sort', sort && sort.value || 'date-desc');
return params.toString();
}
async function refreshItems() {
var requestSequence = ++refreshSequence;
try {
var response = await fetch('/media-library/assets?' + getQueryParams(0, 4 * getColumnsPerRow()), { credentials: 'same-origin', headers: { Accept: 'application/json' } });
if (!response.ok) {
return;
}
var payload = await response.json();
if (requestSequence !== refreshSequence) {
return;
}
loadedAssets = Array.isArray(payload.assets) ? payload.assets : [];
mediaOffset = Number(payload.nextOffset || loadedAssets.length);
mediaHasMore = Boolean(payload.hasMore);
renderItems(loadedAssets);
updateSelection();
applyFilterAndSort();
} catch (_error) {
// Keep the server-rendered list if refreshing is unavailable.
}
}
function escapeHtml(value) {
return String(value || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function showModal() {
if (window.pulseModal && typeof window.pulseModal.show === 'function') {
window.pulseModal.show(modal);
} else if (window.bootstrap && window.bootstrap.Modal) {
window.bootstrap.Modal.getOrCreateInstance(modal).show();
}
}
function hideModal() {
if (window.pulseModal && typeof window.pulseModal.hide === 'function') {
window.pulseModal.hide(modal);
} else if (window.bootstrap && window.bootstrap.Modal) {
window.bootstrap.Modal.getOrCreateInstance(modal).hide();
}
}
function applyFilterAndSort() {
var visibleItems = items.slice();
var columnsPerRow = getColumnsPerRow();
var visibleItemLimit = visibleRowLimit * columnsPerRow;
items.forEach(function (item) { item.hidden = true; });
visibleItems.slice(0, visibleItemLimit).forEach(function (item) {
item.hidden = false;
if (grid) grid.appendChild(item);
});
if (noResults) noResults.hidden = visibleItems.length > 0;
if (loadMoreWrap) loadMoreWrap.hidden = !mediaHasMore || visibleItems.length === 0;
}
function resetVisibleItemLimit() {
visibleRowLimit = 4;
if (activeButton) {
refreshItems();
}
}
function updateSelection() {
items.forEach(function (item) {
var itemButton = item.querySelector('[data-media-picker-path]');
var path = itemButton && itemButton.getAttribute('data-media-picker-path');
var current = Boolean(currentPath && path === currentPath);
var selected = Boolean(pendingPath && path === pendingPath);
item.classList.toggle('media-picker-item-current-card', current);
item.classList.toggle('media-picker-item-selected-card', selected);
if (itemButton) {
itemButton.setAttribute('aria-pressed', selected ? 'true' : 'false');
var currentLabel = itemButton.querySelector('[data-media-picker-current]');
if (currentLabel) currentLabel.hidden = !current;
var selectedLabel = itemButton.querySelector('[data-media-picker-selected]');
if (selectedLabel) selectedLabel.hidden = !selected;
}
});
}
function getActiveHidden() {
var hiddenKey = activeButton && activeButton.getAttribute('data-media-picker-hidden');
return hiddenKey && (document.getElementById(hiddenKey) || document.querySelector('[name="' + hiddenKey + '"]'));
}
function closePicker() {
activeButton = null;
currentPath = '';
pendingPath = '';
pendingType = '';
hideModal();
}
function getActiveFileInput() {
if (!activeButton) {
return null;
}
var explicitInputId = activeButton.getAttribute('data-media-picker-file-input');
if (explicitInputId) {
var explicitInput = document.getElementById(explicitInputId);
if (explicitInput) {
return explicitInput;
}
}
var hiddenKey = activeButton.getAttribute('data-media-picker-hidden');
if (hiddenKey) {
var inputFromHidden = document.getElementById(hiddenKey.replace(/^existing[-_]/, ''));
if (inputFromHidden) {
return inputFromHidden;
}
}
var inputId = activeButton.getAttribute('for');
if (inputId) {
return document.getElementById(inputId);
}
var region = activeButton.closest ? activeButton.closest('[data-region-id]') : null;
return region ? region.querySelector('input[type="file"]') : null;
}
function updatePreview(hidden, path, type) {
var region = hidden.closest ? hidden.closest('[data-region-id]') : null;
if (region) {
var previewBox = region.querySelector('.slide-image-region-preview-box');
if (previewBox) {
var safePath = escapeHtml(path);
previewBox.innerHTML = type === 'video'
? '<div class="slide-image-region-preview-shell"><video class="slide-image-region-preview" src="' + safePath + '" muted playsinline preload="metadata"></video></div>'
: '<div class="slide-image-region-preview-shell"><img class="slide-image-region-preview" src="' + safePath + '" alt="Selected media preview" /></div>';
}
return;
}
var backgroundPreview = document.getElementById('background-preview');
var backgroundEmpty = document.getElementById('background-empty');
if (backgroundPreview && path) {
backgroundPreview.src = path;
backgroundPreview.style.display = 'block';
if (backgroundEmpty) backgroundEmpty.style.display = 'none';
}
}
document.addEventListener('click', function (event) {
var uploadTrigger = event.target && event.target.closest ? event.target.closest('[data-media-picker-upload]') : null;
if (uploadTrigger) {
event.preventDefault();
var fileInput = getActiveFileInput();
if (fileInput) {
fileInput.addEventListener('click', function (inputEvent) {
inputEvent.stopPropagation();
}, { once: true });
fileInput.click();
closePicker();
}
return;
}
var button = event.target && event.target.closest ? event.target.closest('[data-media-picker]') : null;
if (button) {
event.preventDefault();
activeButton = button;
var hidden = getActiveHidden();
currentPath = hidden ? String(hidden.value || '') : '';
pendingPath = currentPath;
pendingType = button.getAttribute('data-media-picker-type') || 'image';
if (search) search.value = '';
if (sort) sort.value = 'date-desc';
visibleRowLimit = 4;
updateSelection();
applyFilterAndSort();
showModal();
refreshItems();
return;
}
var itemButton = event.target && event.target.closest ? event.target.closest('[data-media-picker-path]') : null;
if (!itemButton || !activeButton) {
return;
}
pendingPath = itemButton.getAttribute('data-media-picker-path') || '';
pendingType = itemButton.getAttribute('data-media-picker-type') || activeButton.getAttribute('data-media-picker-type') || 'image';
updateSelection();
});
if (search) search.addEventListener('input', resetVisibleItemLimit);
if (sort) sort.addEventListener('change', resetVisibleItemLimit);
if (loadMoreButton) loadMoreButton.addEventListener('click', async function () {
loadMoreButton.disabled = true;
try {
var response = await fetch('/media-library/assets?' + getQueryParams(mediaOffset, 4 * getColumnsPerRow()), { credentials: 'same-origin', headers: { Accept: 'application/json' } });
if (!response.ok) {
return;
}
var payload = await response.json();
loadedAssets = loadedAssets.concat(Array.isArray(payload.assets) ? payload.assets : []);
mediaOffset = Number(payload.nextOffset || mediaOffset);
mediaHasMore = Boolean(payload.hasMore);
renderItems(loadedAssets);
visibleRowLimit += 4;
updateSelection();
applyFilterAndSort();
} finally {
loadMoreButton.disabled = false;
}
});
if (confirmButton) confirmButton.addEventListener('click', function () {
var hidden = getActiveHidden();
if (!hidden || !pendingPath) {
closePicker();
return;
}
hidden.value = pendingPath;
updatePreview(hidden, pendingPath, pendingType);
hidden.dispatchEvent(new Event('change', { bubbles: true }));
closePicker();
});
if (cancelButton) cancelButton.addEventListener('click', closePicker);
modal.addEventListener('hidden.bs.modal', function () {
activeButton = null;
currentPath = '';
pendingPath = '';
pendingType = '';
});
})();
+6
View File
@@ -106,6 +106,9 @@
} }
var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression); var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression);
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(expression)) {
return placeholderUtils.renderProgressPlaceholder(item, expression);
}
if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) { if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) {
var imageSource = placeholderUtils.formatPlaceholderValue(resolved); var imageSource = placeholderUtils.formatPlaceholderValue(resolved);
if (!/^(?:https?:\/\/|\/media\/|\/assets\/|\/[^/])/i.test(imageSource)) { if (!/^(?:https?:\/\/|\/media\/|\/assets\/|\/[^/])/i.test(imageSource)) {
@@ -164,8 +167,11 @@
'<div class="offcanvas-body">' + '<div class="offcanvas-body">' +
'<p class="small text-body-secondary">Placeholders read values from the selected API item. Nested fields use dots.</p>' + '<p class="small text-body-secondary">Placeholders read values from the selected API item. Nested fields use dots.</p>' +
(window.placeholderInfo ? window.placeholderInfo.renderTextTransforms() : '') + (window.placeholderInfo ? window.placeholderInfo.renderTextTransforms() : '') +
(window.placeholderInfo ? window.placeholderInfo.renderMathTransforms() : '') +
(window.placeholderInfo ? window.placeholderInfo.renderDateFormatTokens() : '') + (window.placeholderInfo ? window.placeholderInfo.renderDateFormatTokens() : '') +
(window.placeholderInfo ? window.placeholderInfo.renderImageTransform() : '') + (window.placeholderInfo ? window.placeholderInfo.renderImageTransform() : '') +
'<h3 class="fs-6 mt-4 fw-normal">Progress bar</h3>' +
'<p class="small">Use <code>{{progress(current,total,success,light,striped,animated,textless)}}</code> to render a configurable bar, or use start and end date/time fields such as <code>{{progress(start_datetime,end_datetime)}}</code> to show elapsed time. The first color controls the bar and the second controls its background. Choose AdminLTE or announcement colors such as <code>orange</code> or <code>midnight</code>, a hex color, <code>striped</code>, <code>animated</code>, or <code>textless</code> in any order. Set the radius with <code>square</code>, <code>pill</code>, or <code>radius(12px)</code>. The bar height follows the API region text size, and all options after the two field paths are optional.</p>' +
'</div>' + '</div>' +
'</div>'; '</div>';
} }
+1 -1
View File
@@ -44,7 +44,7 @@
function renderPreview(region, value) { function renderPreview(region, value) {
var html = normalizePreviewValue(value !== undefined ? value : region).trim(); var html = normalizePreviewValue(value !== undefined ? value : region).trim();
if (!html) { if (!html) {
return '<div class="slide-preview-placeholder">HTML</div>'; return '';
} }
if (/^<!doctype\b/i.test(html) || /^<html\b/i.test(html)) { if (/^<!doctype\b/i.test(html) || /^<html\b/i.test(html)) {
return '<iframe class="slide-preview-html-frame" sandbox="" allowtransparency="true" scrolling="no" srcdoc="' + escapeHtml(buildHtmlDocument(html)) + '" title="HTML preview" loading="eager" style="width:100%;height:100%;border:0;display:block;background:transparent;overflow:hidden;"></iframe>'; return '<iframe class="slide-preview-html-frame" sandbox="" allowtransparency="true" scrolling="no" srcdoc="' + escapeHtml(buildHtmlDocument(html)) + '" title="HTML preview" loading="eager" style="width:100%;height:100%;border:0;display:block;background:transparent;overflow:hidden;"></iframe>';
+3 -3
View File
@@ -21,7 +21,7 @@
var content = value && typeof value === 'object' && value.value !== undefined ? value : null; var content = value && typeof value === 'object' && value.value !== undefined ? value : null;
var src = String(content ? content.value : value || '').trim(); var src = String(content ? content.value : value || '').trim();
if (!src) { if (!src) {
return '<div class="slide-preview-placeholder">Image</div>'; return '';
} }
return '<img class="slide-preview-image" src="' + escapeHtml(src) + '" alt="" style="width:100%;height:100%;object-fit:contain;display:block;" />'; return '<img class="slide-preview-image" src="' + escapeHtml(src) + '" alt="" style="width:100%;height:100%;object-fit:contain;display:block;" />';
} }
@@ -41,12 +41,12 @@
bodyHtml: '' + bodyHtml: '' +
'<div class="row g-3 align-items-start">' + '<div class="row g-3 align-items-start">' +
'<div class="col-12 col-md-8 d-flex flex-column">' + '<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 + '">' + '<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" data-media-picker data-media-picker-type="image" data-media-picker-hidden="existing_region_image_' + region.id + '" for="region_image_' + region.id + '">' +
'<input type="file" id="region_image_' + region.id + '" name="region_image_' + region.id + '" class="visually-hidden" accept="' + escapeHtml(uploadAccept) + '" data-slide-image-cropper-region-ratio="' + escapeHtml(regionRatio) + '" data-slide-image-cropper-region-ratio-label="Region" />' + '<input type="file" id="region_image_' + region.id + '" name="region_image_' + region.id + '" class="visually-hidden" accept="' + escapeHtml(uploadAccept) + '" data-slide-image-cropper-region-ratio="' + escapeHtml(regionRatio) + '" data-slide-image-cropper-region-ratio-label="Region" />' +
'<span class="slide-image-region-upload-zone-content">' + '<span class="slide-image-region-upload-zone-content">' +
'<span class="slide-image-region-upload-zone-icon"><i class="bi bi-cloud-arrow-up" aria-hidden="true"></i></span>' + '<span class="slide-image-region-upload-zone-icon"><i class="bi bi-cloud-arrow-up" aria-hidden="true"></i></span>' +
'<span class="slide-image-region-upload-zone-copy">' + '<span class="slide-image-region-upload-zone-copy">' +
'<strong>Drop an image here or click to upload</strong>' + '<strong>Drop an image here or click to select existing</strong>' +
'<span>' + escapeHtml(uploadHelpText) + '</span>' + '<span>' + escapeHtml(uploadHelpText) + '</span>' +
'<span class="slide-image-region-upload-zone-limit">Max ' + escapeHtml(uploadMaxLabel) + ' per file</span>' + '<span class="slide-image-region-upload-zone-limit">Max ' + escapeHtml(uploadMaxLabel) + ' per file</span>' +
'</span>' + '</span>' +
+3 -3
View File
@@ -880,7 +880,7 @@
src = svgSrc || buildStyledQrSvgMarkup(value); src = svgSrc || buildStyledQrSvgMarkup(value);
} }
if (!src) { if (!src) {
return '<div class="slide-preview-placeholder">QR Code</div>'; return '';
} }
if (/^data:image\//i.test(src)) { if (/^data:image\//i.test(src)) {
return '<img class="slide-preview-qr-code" src="' + escapeHtml(src) + '" alt="QR code preview" style="' + imageStyle + '" />'; return '<img class="slide-preview-qr-code" src="' + escapeHtml(src) + '" alt="QR code preview" style="' + imageStyle + '" />';
@@ -982,12 +982,12 @@
var imageOptionsHtml = '' + var imageOptionsHtml = '' +
'<div class="row g-3 align-items-start">' + '<div class="row g-3 align-items-start">' +
'<div class="col-12 col-md-8">' + '<div class="col-12 col-md-8">' +
'<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" for="region_qr_image_' + region.id + '">' + '<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" data-media-picker data-media-picker-type="image" data-media-picker-hidden="existing_region_qr_image_' + region.id + '" for="region_qr_image_' + region.id + '">' +
'<input type="file" id="region_qr_image_' + region.id + '" name="region_qr_image_' + region.id + '" class="visually-hidden" accept="image/*" />' + '<input type="file" id="region_qr_image_' + region.id + '" name="region_qr_image_' + region.id + '" class="visually-hidden" accept="image/*" />' +
'<span class="slide-image-region-upload-zone-content">' + '<span class="slide-image-region-upload-zone-content">' +
'<span class="slide-image-region-upload-zone-icon"><i class="bi bi-cloud-arrow-up" aria-hidden="true"></i></span>' + '<span class="slide-image-region-upload-zone-icon"><i class="bi bi-cloud-arrow-up" aria-hidden="true"></i></span>' +
'<span class="slide-image-region-upload-zone-copy">' + '<span class="slide-image-region-upload-zone-copy">' +
'<strong>Drop an image here or click to upload</strong>' + '<strong>Drop an image here or click to select existing</strong>' +
'<span>PNG, JPG, GIF, or WebP</span>' + '<span>PNG, JPG, GIF, or WebP</span>' +
'<span class="slide-image-region-upload-zone-limit">Replaces the QR image logo</span>' + '<span class="slide-image-region-upload-zone-limit">Replaces the QR image logo</span>' +
'</span>' + '</span>' +
+6 -2
View File
@@ -125,6 +125,9 @@
return ''; return '';
} }
var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression); var resolved = placeholderUtils.resolvePlaceholderExpression(item, expression);
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(expression)) {
return placeholderUtils.renderProgressPlaceholder(item, expression);
}
if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) { if (typeof placeholderUtils.isImagePlaceholderExpression === 'function' && placeholderUtils.isImagePlaceholderExpression(expression)) {
var imageSource = placeholderUtils.formatPlaceholderValue(resolved); var imageSource = placeholderUtils.formatPlaceholderValue(resolved);
if (!/^(?:https?:\/\/|\/media\/|\/assets\/|\/[^/])/i.test(imageSource)) { if (!/^(?:https?:\/\/|\/media\/|\/assets\/|\/[^/])/i.test(imageSource)) {
@@ -155,7 +158,7 @@
function getPreviewFallback(item) { function getPreviewFallback(item) {
if (!item || typeof item !== 'object') { if (!item || typeof item !== 'object') {
return '<div class="slide-preview-placeholder">RSS item</div>'; return '';
} }
var title = String(item.title || '').trim(); var title = String(item.title || '').trim();
@@ -168,7 +171,7 @@
summary.push('<p>' + sanitizePreviewHtml(description) + '</p>'); summary.push('<p>' + sanitizePreviewHtml(description) + '</p>');
} }
if (!summary.length) { if (!summary.length) {
return '<div class="slide-preview-placeholder">RSS item</div>'; return '';
} }
return summary.join(''); return summary.join('');
} }
@@ -224,6 +227,7 @@
'<h3 class="fs-6 mt-4 fw-normal">Placeholder paths</h3>' + '<h3 class="fs-6 mt-4 fw-normal">Placeholder paths</h3>' +
'<p class="small">Nested values use dots. Missing values render as empty text.</p>' + '<p class="small">Nested values use dots. Missing values render as empty text.</p>' +
(window.placeholderInfo ? window.placeholderInfo.renderTextTransforms() : '') + (window.placeholderInfo ? window.placeholderInfo.renderTextTransforms() : '') +
(window.placeholderInfo ? window.placeholderInfo.renderMathTransforms() : '') +
'<h3 class="fs-6 mt-4 fw-normal">Date formatting</h3>' + '<h3 class="fs-6 mt-4 fw-normal">Date formatting</h3>' +
'<p class="small">Use <code>format("MMM D, YYYY")</code> with date fields. Use <code>tz()</code> for a short timezone name and <code>tz_long()</code> for the full timezone name.</p>' + '<p class="small">Use <code>format("MMM D, YYYY")</code> with date fields. Use <code>tz()</code> for a short timezone name and <code>tz_long()</code> for the full timezone name.</p>' +
(window.placeholderInfo ? window.placeholderInfo.renderDateFormatTokens() : '') + (window.placeholderInfo ? window.placeholderInfo.renderDateFormatTokens() : '') +
+4 -1
View File
@@ -11,7 +11,10 @@
function renderPreview(value, disableAudio) { function renderPreview(value, disableAudio) {
var content = value && typeof value === 'object' && value.value !== undefined ? value : null; var content = value && typeof value === 'object' && value.value !== undefined ? value : null;
var src = String(content ? content.value : value || '').trim(); var src = String(content ? content.value : value || '').trim();
var label = src ? 'RTMP' : 'RTMP stream'; if (!src) {
return '';
}
var label = 'RTMP';
if (disableAudio) { if (disableAudio) {
label += ' (muted)'; label += ' (muted)';
} }
+1 -1
View File
@@ -29,7 +29,7 @@
var rawValue = value && typeof value === 'object' && value.value !== undefined ? value.value : value; var rawValue = value && typeof value === 'object' && value.value !== undefined ? value.value : value;
var raw = String(rawValue || ''); var raw = String(rawValue || '');
if (!raw) { if (!raw) {
return '<div class="slide-preview-placeholder">Empty text</div>'; return '';
} }
var style = styleOrContext && styleOrContext.style ? styleOrContext.style : styleOrContext || {}; var style = styleOrContext && styleOrContext.style ? styleOrContext.style : styleOrContext || {};
+5 -2
View File
@@ -155,7 +155,7 @@
dddd: toTitleCase(getPart(weekdayLong, 'weekday')), dddd: toTitleCase(getPart(weekdayLong, 'weekday')),
MMM: toTitleCase(getPart(monthShort, 'month')), MMM: toTitleCase(getPart(monthShort, 'month')),
MMMM: toTitleCase(getPart(monthLong, 'month')), MMMM: toTitleCase(getPart(monthLong, 'month')),
a: toTitleCase(getPart(ampm, 'dayPeriod')), a: String(getPart(ampm, 'dayPeriod') || '').toLowerCase(),
tz: getPart(getFormatter('tz-short:' + resolvedTimeZone, { tz: getPart(getFormatter('tz-short:' + resolvedTimeZone, {
timeZone: resolvedTimeZone, timeZone: resolvedTimeZone,
timeZoneName: 'short' timeZoneName: 'short'
@@ -296,7 +296,10 @@
var table = '<div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Placeholder</th><th>Output</th><th>Description</th></tr></thead><tbody>' + placeholders.map(function (item) { var table = '<div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Placeholder</th><th>Output</th><th>Description</th></tr></thead><tbody>' + placeholders.map(function (item) {
return '<tr><td><code>{{' + escapeHtml(item.token) + '}}</code></td><td>' + escapeHtml(item.output) + '</td><td>' + escapeHtml(item.description) + '</td></tr>'; return '<tr><td><code>{{' + escapeHtml(item.token) + '}}</code></td><td>' + escapeHtml(item.output) + '</td><td>' + escapeHtml(item.description) + '</td></tr>';
}).join('') + '</tbody></table></div>'; }).join('') + '</tbody></table></div>';
return window.placeholderInfo.render(regionId, 'Time and date placeholders', table); var transforms = '' +
(typeof window.placeholderInfo.renderTextTransforms === 'function' ? window.placeholderInfo.renderTextTransforms() : '') +
(typeof window.placeholderInfo.renderMathTransforms === 'function' ? window.placeholderInfo.renderMathTransforms() : '');
return window.placeholderInfo.render(regionId, 'Time and date placeholders', table + transforms);
} }
function renderEditorCard(context) { function renderEditorCard(context) {
@@ -140,6 +140,9 @@
if (placeholderUtils && typeof placeholderUtils.resolvePlaceholderExpression === 'function' && typeof placeholderUtils.formatPlaceholderValue === 'function') { if (placeholderUtils && typeof placeholderUtils.resolvePlaceholderExpression === 'function' && typeof placeholderUtils.formatPlaceholderValue === 'function') {
return source.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, function (_match, expression) { return source.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, function (_match, expression) {
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(expression)) {
return placeholderUtils.renderProgressPlaceholder(context, expression);
}
return escapeHtml(placeholderUtils.formatPlaceholderValue(placeholderUtils.resolvePlaceholderExpression(context, expression))); return escapeHtml(placeholderUtils.formatPlaceholderValue(placeholderUtils.resolvePlaceholderExpression(context, expression)));
}); });
} }
@@ -248,6 +251,7 @@
'<h3 class="fs-6 mt-4 fw-normal">Placeholder paths</h3>' + '<h3 class="fs-6 mt-4 fw-normal">Placeholder paths</h3>' +
'<p class="small">Use the available field chips. Nested values use dots, and missing values render as empty text.</p>' + '<p class="small">Use the available field chips. Nested values use dots, and missing values render as empty text.</p>' +
window.placeholderInfo.renderTextTransforms() + window.placeholderInfo.renderTextTransforms() +
window.placeholderInfo.renderMathTransforms() +
'<h3 class="fs-6 mt-4 fw-normal">Date and time formatting</h3>' + '<h3 class="fs-6 mt-4 fw-normal">Date and time formatting</h3>' +
'<p class="small">Use <code>format("MMM D, YYYY h:mm A")</code> with date fields. Use <code>tz()</code> for a short timezone name and <code>tz_long()</code> for the full timezone name.</p>' + '<p class="small">Use <code>format("MMM D, YYYY h:mm A")</code> with date fields. Use <code>tz()</code> for a short timezone name and <code>tz_long()</code> for the full timezone name.</p>' +
window.placeholderInfo.renderDateFormatTokens() + window.placeholderInfo.renderDateFormatTokens() +
+3 -3
View File
@@ -26,7 +26,7 @@
var content = value && typeof value === 'object' && value.value !== undefined ? value : null; var content = value && typeof value === 'object' && value.value !== undefined ? value : null;
var src = String(content ? content.value : value || '').trim(); var src = String(content ? content.value : value || '').trim();
if (!src) { if (!src) {
return '<div class="slide-preview-placeholder">Video</div>'; return '';
} }
return '<video class="slide-preview-video" src="' + escapeHtml(src) + '" autoplay loop muted playsinline preload="metadata" style="width:100%;height:100%;object-fit:contain;display:block;"></video>'; return '<video class="slide-preview-video" src="' + escapeHtml(src) + '" autoplay loop muted playsinline preload="metadata" style="width:100%;height:100%;object-fit:contain;display:block;"></video>';
} }
@@ -46,12 +46,12 @@
bodyHtml: '' + bodyHtml: '' +
'<div class="row g-3 align-items-start">' + '<div class="row g-3 align-items-start">' +
'<div class="col-12 col-md-8 d-flex flex-column">' + '<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 + '">' + '<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" data-media-picker data-media-picker-type="video" data-media-picker-hidden="existing_region_video_' + region.id + '" for="region_video_' + region.id + '">' +
'<input type="file" id="region_video_' + region.id + '" name="region_video_' + region.id + '" class="visually-hidden" accept="' + escapeHtml(uploadAccept) + '" />' + '<input type="file" id="region_video_' + region.id + '" name="region_video_' + region.id + '" class="visually-hidden" accept="' + escapeHtml(uploadAccept) + '" />' +
'<span class="slide-image-region-upload-zone-content">' + '<span class="slide-image-region-upload-zone-content">' +
'<span class="slide-image-region-upload-zone-icon"><i class="bi bi-camera-video" aria-hidden="true"></i></span>' + '<span class="slide-image-region-upload-zone-icon"><i class="bi bi-camera-video" aria-hidden="true"></i></span>' +
'<span class="slide-image-region-upload-zone-copy">' + '<span class="slide-image-region-upload-zone-copy">' +
'<strong>Drop a video here or click to upload</strong>' + '<strong>Drop a video here or click to select existing</strong>' +
'<span>' + escapeHtml(uploadHelpText) + '</span>' + '<span>' + escapeHtml(uploadHelpText) + '</span>' +
'<span class="slide-image-region-upload-zone-limit">Max ' + escapeHtml(uploadVideoMaxLabel) + ' per file</span>' + '<span class="slide-image-region-upload-zone-limit">Max ' + escapeHtml(uploadVideoMaxLabel) + ' per file</span>' +
'</span>' + '</span>' +
+7 -2
View File
@@ -114,6 +114,9 @@
if (!value || typeof value !== 'object' || typeof placeholderUtils.resolvePlaceholderExpression !== 'function' || typeof placeholderUtils.formatPlaceholderValue !== 'function') return ''; if (!value || typeof value !== 'object' || typeof placeholderUtils.resolvePlaceholderExpression !== 'function' || typeof placeholderUtils.formatPlaceholderValue !== 'function') return '';
var rawExpression = String(expression).trim(); var rawExpression = String(expression).trim();
var normalizedExpression = normalizeWeatherExpression(rawExpression); var normalizedExpression = normalizeWeatherExpression(rawExpression);
if (typeof placeholderUtils.isProgressPlaceholderExpression === 'function' && placeholderUtils.isProgressPlaceholderExpression(rawExpression)) {
return placeholderUtils.renderProgressPlaceholder(value, rawExpression);
}
var iconMatch = normalizedExpression.match(/^(?:current\.weather_code|daily\.weather_code\.\d+|hourly\.weather_code\.\d+)\.icon(?:\((\d+)(?:\s*,\s*(\d+))?\))?$/); var iconMatch = normalizedExpression.match(/^(?:current\.weather_code|daily\.weather_code\.\d+|hourly\.weather_code\.\d+)\.icon(?:\((\d+)(?:\s*,\s*(\d+))?\))?$/);
if (iconMatch) { if (iconMatch) {
var codeExpression = normalizedExpression.replace(/\.icon(?:\(.*\))?$/, ''); var codeExpression = normalizedExpression.replace(/\.icon(?:\(.*\))?$/, '');
@@ -137,6 +140,7 @@
'<div class="offcanvas-body"><p class="small text-body-secondary">Placeholders read values from the selected weather snapshot. Nested fields use dots.</p>' + '<div class="offcanvas-body"><p class="small text-body-secondary">Placeholders read values from the selected weather snapshot. Nested fields use dots.</p>' +
'<h3 class="h6 mt-3">Weather icons</h3><p class="small text-body-secondary">Use the icon property to insert a Bootstrap weather icon. Add width and height in pixels when sizing is needed.</p><ul class="small"><li><code>{{current.icon}}</code></li><li><code>{{current.icon(48,48)}}</code></li><li><code>{{daily.0.icon(32,24)}}</code></li></ul>' + '<h3 class="h6 mt-3">Weather icons</h3><p class="small text-body-secondary">Use the icon property to insert a Bootstrap weather icon. Add width and height in pixels when sizing is needed.</p><ul class="small"><li><code>{{current.icon}}</code></li><li><code>{{current.icon(48,48)}}</code></li><li><code>{{daily.0.icon(32,24)}}</code></li></ul>' +
(window.placeholderInfo ? window.placeholderInfo.renderTextTransforms() : '') + (window.placeholderInfo ? window.placeholderInfo.renderTextTransforms() : '') +
(window.placeholderInfo ? window.placeholderInfo.renderMathTransforms() : '') +
(window.placeholderInfo ? window.placeholderInfo.renderDateFormatTokens() : '') + (window.placeholderInfo ? window.placeholderInfo.renderDateFormatTokens() : '') +
'</div>' + '</div>' +
'</div>'; '</div>';
@@ -144,10 +148,11 @@
function renderPreview(region, content, context) { function renderPreview(region, content, context) {
var locations = context && context.weatherLocations ? context.weatherLocations : []; var locations = context && context.weatherLocations ? context.weatherLocations : [];
var value = String(content && content.value || '');
if (!value.trim()) return '';
var location = getLocationById(content && content.weather_location_id, locations); var location = getLocationById(content && content.weather_location_id, locations);
var snapshot = getSnapshot(location); var snapshot = getSnapshot(location);
var value = String(content && content.value || ''); if (!location || !snapshot) return '';
if (!location || !snapshot) return '<div class="template-region weather"><div class="slide-preview-placeholder">Select a weather location with cached data</div></div>';
var weatherData = withWeatherUnits(snapshot, location); var weatherData = withWeatherUnits(snapshot, location);
if (value) { if (value) {
var fontSize = Math.max(8, Number(content && content.font_size || region && (region.font_size || region.fontSize) || 32) || 32); var fontSize = Math.max(8, Number(content && content.font_size || region && (region.font_size || region.fontSize) || 32) || 32);
+1 -1
View File
@@ -37,7 +37,7 @@
function renderPreview(region, value) { function renderPreview(region, value) {
var src = normalizePreviewValue(value !== undefined ? value : region).trim(); var src = normalizePreviewValue(value !== undefined ? value : region).trim();
if (!src) { if (!src) {
return '<div class="slide-preview-placeholder">Webpage</div>'; return '';
} }
return '<iframe class="slide-preview-webpage-frame" src="' + escapeHtml(src) + '" title="Webpage preview" loading="eager" referrerpolicy="no-referrer" scrolling="no" style="width:100%;height:100%;border:0;display:block;background:#fff;overflow:hidden;"></iframe>'; return '<iframe class="slide-preview-webpage-frame" src="' + escapeHtml(src) + '" title="Webpage preview" loading="eager" referrerpolicy="no-referrer" scrolling="no" style="width:100%;height:100%;border:0;display:block;background:#fff;overflow:hidden;"></iframe>';
} }
+573
View File
@@ -0,0 +1,573 @@
const modal = document.getElementById('media-gallery-preview-modal');
const body = modal && modal.querySelector('[data-media-gallery-preview-body]');
const title = modal && modal.querySelector('#media-gallery-preview-modal-label');
const gallery = document.querySelector('.media-gallery');
const search = gallery && gallery.querySelector('[data-media-gallery-search]');
const typeFilter = gallery && gallery.querySelector('[data-media-gallery-type-filter]');
const usageFilter = gallery && gallery.querySelector('[data-media-gallery-usage-filter]');
const sort = gallery && gallery.querySelector('[data-media-gallery-sort]');
const galleryCount = gallery && gallery.querySelector('[data-media-gallery-count]');
const noResults = gallery && gallery.querySelector('[data-media-gallery-no-results]');
const loadMoreWrap = gallery && gallery.querySelector('[data-media-gallery-load-more-wrap]');
const loadMoreButton = gallery && gallery.querySelector('[data-media-gallery-load-more]');
const selectModeButton = gallery && gallery.querySelector('[data-media-gallery-select-mode]');
const deleteSelectedButton = gallery && gallery.querySelector('[data-media-gallery-delete-selected]');
const addMediaButton = gallery && gallery.querySelector('[data-media-library-add]');
let galleryItems = gallery ? Array.from(gallery.querySelectorAll('[data-media-gallery-column]')) : [];
let visibleRowLimit = 4;
let galleryOffset = gallery ? Number(gallery.dataset.mediaGalleryOffset || galleryItems.length) : 0;
let galleryHasMore = gallery ? gallery.dataset.mediaGalleryHasMore === 'true' : false;
let galleryTotal = galleryCount ? Number(galleryCount.textContent || galleryItems.length) : galleryItems.length;
let galleryRefreshSequence = 0;
let selectionMode = false;
const selectedAssetIds = new Set();
const uploadForm = document.querySelector('form[action="/media-library"]');
const uploadInput = document.querySelector('[data-media-library-upload]');
const uploadZone = document.querySelector('[data-media-library-upload-zone]');
const uploadName = document.querySelector('[data-media-library-upload-name]');
const uploadModal = document.getElementById('media-library-upload-modal');
const cropModal = document.getElementById('media-library-crop-modal');
const cropImage = cropModal && cropModal.querySelector('#media-library-crop-image');
const cropApply = cropModal && cropModal.querySelector('[data-media-library-crop-apply]');
const cropCancel = cropModal && cropModal.querySelector('[data-media-library-crop-cancel]');
const cropStatus = cropModal && cropModal.querySelector('#media-library-crop-status');
const cropFrame = cropModal && cropModal.querySelector('.slide-image-cropper-frame');
let cropper = null;
let cropObjectUrl = '';
let cropSourceFile = null;
let cropFlipX = 1;
let cropFlipY = 1;
function getColumnsPerRow() {
return window.innerWidth >= 1200 ? 6 : window.innerWidth >= 992 ? 3 : window.innerWidth >= 576 ? 2 : 1;
}
function showUploadMessage(message) {
if (typeof window.showToast === 'function') {
window.showToast(message, 'warning');
return;
}
window.alert(message);
}
function showModal(target) {
if (window.pulseModal && typeof window.pulseModal.show === 'function') {
window.pulseModal.show(target);
} else if (window.bootstrap && window.bootstrap.Modal) {
window.bootstrap.Modal.getOrCreateInstance(target).show();
}
}
function hideModal(target) {
if (window.pulseModal && typeof window.pulseModal.hide === 'function') {
window.pulseModal.hide(target);
} else if (window.bootstrap && window.bootstrap.Modal) {
window.bootstrap.Modal.getOrCreateInstance(target).hide();
}
}
if (addMediaButton && uploadModal) {
addMediaButton.addEventListener('click', function () {
showModal(uploadModal);
});
}
function clearCropper() {
if (cropper) {
cropper.destroy();
cropper = null;
}
if (cropObjectUrl) {
URL.revokeObjectURL(cropObjectUrl);
cropObjectUrl = '';
}
cropSourceFile = null;
cropFlipX = 1;
cropFlipY = 1;
if (cropStatus) cropStatus.textContent = '';
if (cropFrame) cropFrame.classList.remove('is-loading');
}
function setCropperActionState(disabled) {
if (!cropModal) return;
cropModal.querySelectorAll('[data-media-library-crop-action]').forEach(function (button) {
button.disabled = Boolean(disabled);
});
}
function appendGalleryAsset(asset) {
if (!gallery || !asset) return;
const column = document.createElement('div');
column.className = 'col-12 col-sm-6 col-lg-4 col-xl-2';
column.dataset.mediaGalleryColumn = '';
column.dataset.mediaId = String(asset.id || '');
column.dataset.mediaType = asset.media_type || '';
column.dataset.mediaUsed = asset.inUse ? 'true' : 'false';
const article = document.createElement('article');
article.className = 'media-gallery-card';
article.dataset.mediaCreatedAt = asset.created_at || '';
article.dataset.mediaFileSize = asset.file_size || '0';
const preview = document.createElement('button');
preview.type = 'button';
preview.className = 'media-gallery-preview';
preview.dataset.mediaGalleryPreview = '';
preview.dataset.mediaPath = asset.media_path || '';
preview.dataset.mediaType = asset.media_type || '';
preview.dataset.mediaName = asset.original_name || '';
preview.setAttribute('aria-label', 'Preview ' + (asset.original_name || 'media'));
const media = asset.media_type === 'video' ? document.createElement('video') : document.createElement('img');
media.src = asset.media_path || '';
if (asset.media_type === 'video') {
media.muted = true;
media.playsInline = true;
media.preload = 'metadata';
} else {
media.alt = asset.original_name || '';
media.loading = 'lazy';
}
preview.appendChild(media);
if (asset.media_type === 'video') {
const play = document.createElement('span');
play.className = 'media-gallery-play';
play.setAttribute('aria-hidden', 'true');
play.innerHTML = '<i class="bi bi-play-fill"></i>';
preview.appendChild(play);
}
const format = document.createElement('span');
format.className = 'media-gallery-type';
format.textContent = asset.mediaFormat || '';
preview.appendChild(format);
const details = document.createElement('div');
details.className = 'media-gallery-details';
const header = document.createElement('div');
header.className = 'media-gallery-header';
const name = document.createElement('h4');
name.className = 'media-gallery-name';
name.title = asset.original_name || '';
name.textContent = asset.original_name || '';
header.appendChild(name);
if (asset.canDelete) {
if (asset.inUse) {
const lock = document.createElement('button');
lock.type = 'button';
lock.className = 'btn btn-outline-secondary btn-sm media-gallery-action';
lock.disabled = true;
lock.title = 'Media is in use';
lock.innerHTML = '<i class="bi bi-lock" aria-hidden="true"></i><span class="visually-hidden">Media is in use</span>';
header.appendChild(lock);
} else {
const form = document.createElement('form');
form.method = 'post';
form.action = '/media-library/' + encodeURIComponent(asset.id) + '/delete';
form.dataset.confirmMessage = 'Delete this media?';
form.className = 'media-gallery-action';
form.innerHTML = '<button type="submit" class="btn btn-outline-danger btn-sm" title="Delete media"><i class="bi bi-trash" aria-hidden="true"></i><span class="visually-hidden">Delete media</span></button>';
header.appendChild(form);
}
}
const meta = document.createElement('div');
meta.className = 'media-gallery-meta';
meta.textContent = (asset.displayFileSize || '') + ' · Used ' + Number(asset.referenceCount || 0) + ' time' + (Number(asset.referenceCount || 0) === 1 ? '' : 's');
details.appendChild(header);
details.appendChild(meta);
article.appendChild(preview);
article.appendChild(details);
column.appendChild(article);
gallery.querySelector('.media-gallery-scroll .row').appendChild(column);
galleryItems.push(column);
column.querySelector('.media-gallery-card').classList.toggle('media-gallery-card-selected', selectedAssetIds.has(String(asset.id || '')));
}
function applyCropRatio(value) {
if (!cropper) return;
cropper.setAspectRatio(value === 'free' ? NaN : Number(value.split(':')[0]) / Number(value.split(':')[1]));
cropModal.querySelectorAll('[data-media-library-crop-action="ratio"]').forEach(function (button) {
const active = button.dataset.mediaLibraryCropRatio === value;
button.classList.toggle('active', active);
button.setAttribute('aria-pressed', active ? 'true' : 'false');
});
}
function initMediaCropper() {
if (!cropSourceFile || !cropImage || !window.Cropper || cropper) return;
if (cropFrame) cropFrame.classList.add('is-loading');
cropper = new window.Cropper(cropImage, {
aspectRatio: NaN,
autoCropArea: 1,
background: false,
dragMode: 'move',
initialAspectRatio: NaN,
movable: true,
responsive: true,
rotatable: true,
scalable: true,
viewMode: 1,
zoomOnTouch: true,
zoomOnWheel: true,
ready: function () {
if (cropFrame) cropFrame.classList.remove('is-loading');
if (cropper && cropper.container) {
cropper.container.style.width = '100%';
cropper.container.style.height = '560px';
cropper.container.style.maxHeight = '70vh';
}
const containerData = cropper.getContainerData();
const imageData = cropper.getImageData();
const fitRatio = Math.min(Number(containerData.width || 0) / Number(imageData.naturalWidth || 1), Number(containerData.height || 0) / Number(imageData.naturalHeight || 1), 1);
if (fitRatio > 0) cropper.zoomTo(fitRatio);
applyCropRatio('free');
setCropperActionState(false);
}
});
}
function setUploadFile(file, shouldCrop) {
if (!uploadInput || !file) {
return;
}
const allowedTypes = String(uploadInput.accept || '').split(',').map(function (value) { return value.trim().toLowerCase(); }).filter(Boolean);
const fileType = String(file.type || '').toLowerCase();
const matchesType = allowedTypes.length === 0 || allowedTypes.indexOf(fileType) !== -1;
const maxBytes = fileType.indexOf('video/') === 0 ? Number(uploadInput.dataset.videoMaxBytes) : Number(uploadInput.dataset.imageMaxBytes);
if (!matchesType) {
showUploadMessage('This media type is disabled in Media Uploads settings.');
uploadInput.value = '';
return;
}
if (maxBytes && file.size > maxBytes) {
showUploadMessage('This file is larger than the configured upload limit.');
uploadInput.value = '';
return;
}
const transfer = new DataTransfer();
transfer.items.add(file);
uploadInput.files = transfer.files;
if (uploadName) {
uploadName.textContent = file.name;
}
if (shouldCrop && fileType.indexOf('image/') === 0 && cropModal && cropImage && window.Cropper) {
clearCropper();
setCropperActionState(true);
cropSourceFile = file;
cropObjectUrl = URL.createObjectURL(file);
cropImage.src = cropObjectUrl;
if (cropFrame) cropFrame.classList.add('is-loading');
showModal(cropModal);
}
}
function submitUpload() {
if (!uploadForm) {
return;
}
if (typeof uploadForm.requestSubmit === 'function') {
uploadForm.requestSubmit();
} else {
uploadForm.submit();
}
}
if (uploadInput) {
uploadInput.addEventListener('change', function () {
const file = uploadInput.files && uploadInput.files[0];
if (file) {
setUploadFile(file, true);
if (String(file.type || '').toLowerCase().indexOf('image/') !== 0 || !(cropModal && cropImage && window.Cropper)) {
submitUpload();
}
}
});
}
if (uploadZone) {
uploadZone.addEventListener('dragover', function (event) {
event.preventDefault();
uploadZone.classList.add('is-dragover');
});
uploadZone.addEventListener('dragleave', function () {
uploadZone.classList.remove('is-dragover');
});
uploadZone.addEventListener('drop', function (event) {
event.preventDefault();
uploadZone.classList.remove('is-dragover');
const file = event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files[0];
if (file) {
setUploadFile(file, true);
if (String(file.type || '').toLowerCase().indexOf('image/') !== 0 || !(cropModal && cropImage && window.Cropper)) {
submitUpload();
}
}
});
}
if (cropApply) {
cropApply.addEventListener('click', function () {
if (!cropper || !cropSourceFile || !uploadInput) {
hideModal(cropModal);
return;
}
const outputType = cropSourceFile.type === 'image/jpeg' || cropSourceFile.type === 'image/webp' ? cropSourceFile.type : 'image/png';
cropper.getCroppedCanvas().toBlob(function (blob) {
if (!blob) {
showUploadMessage('Unable to crop this image.');
return;
}
const extension = outputType === 'image/jpeg' ? '.jpg' : outputType === 'image/webp' ? '.webp' : '.png';
const croppedFile = new File([blob], cropSourceFile.name.replace(/\.[^.]+$/, '') + extension, { type: outputType, lastModified: Date.now() });
clearCropper();
setUploadFile(croppedFile, false);
hideModal(cropModal);
submitUpload();
}, outputType, 0.92);
});
}
if (cropCancel) {
cropCancel.addEventListener('click', function () {
clearCropper();
if (uploadInput) uploadInput.value = '';
if (uploadName) uploadName.textContent = 'No file selected';
hideModal(cropModal);
});
}
if (cropModal) {
cropModal.addEventListener('click', function (event) {
const button = event.target && event.target.closest ? event.target.closest('[data-media-library-crop-action]') : null;
if (!button || !cropper) return;
const action = button.dataset.mediaLibraryCropAction;
if (action === 'rotate-left') cropper.rotate(-90);
if (action === 'rotate-right') cropper.rotate(90);
if (action === 'flip-horizontal') {
cropFlipX *= -1;
cropper.scaleX(cropFlipX);
}
if (action === 'flip-vertical') {
cropFlipY *= -1;
cropper.scaleY(cropFlipY);
}
if (action === 'ratio') applyCropRatio(button.dataset.mediaLibraryCropRatio || 'free');
if (action === 'reset') {
cropper.reset();
cropFlipX = 1;
cropFlipY = 1;
applyCropRatio('free');
}
});
}
if (cropModal) {
cropModal.addEventListener('shown.bs.modal', function () {
if (cropSourceFile && cropImage && window.Cropper && !cropper) {
initMediaCropper();
}
});
cropModal.addEventListener('hidden.bs.modal', function () {
clearCropper();
});
}
if (uploadForm) {
uploadForm.addEventListener('submit', function (event) {
if (uploadInput && !uploadInput.files.length) {
event.preventDefault();
showUploadMessage('Choose an image or video to upload.');
}
});
}
function getGalleryQuery(offset, limit) {
const params = new URLSearchParams();
params.set('offset', String(offset));
params.set('limit', String(limit));
params.set('search', String(search && search.value || '').trim());
params.set('type', typeFilter ? typeFilter.value : 'all');
params.set('usage', usageFilter ? usageFilter.value : 'all');
params.set('sort', sort ? sort.value : 'date-desc');
return params.toString();
}
function updateSearchResults() {
const columnsPerRow = getColumnsPerRow();
const visibleItemLimit = visibleRowLimit * columnsPerRow;
let visibleCount = 0;
galleryItems.forEach(function (card) {
card.hidden = visibleCount >= visibleItemLimit;
if (!card.hidden) {
visibleCount += 1;
}
});
if (galleryCount) {
galleryCount.textContent = String(galleryTotal);
}
if (noResults) {
noResults.hidden = galleryTotal > 0;
}
if (loadMoreWrap) {
loadMoreWrap.hidden = !galleryHasMore || galleryTotal === 0;
}
updateBulkDeleteActions();
}
function updateBulkDeleteActions() {
if (selectModeButton) {
selectModeButton.setAttribute('aria-pressed', selectionMode ? 'true' : 'false');
selectModeButton.textContent = selectionMode ? 'Cancel' : 'Select';
}
if (deleteSelectedButton) {
deleteSelectedButton.hidden = !selectionMode;
deleteSelectedButton.disabled = selectedAssetIds.size === 0;
}
galleryItems.forEach(function (item) {
const id = String(item.dataset.mediaId || '');
const card = item.querySelector('.media-gallery-card');
if (card) {
card.classList.toggle('media-gallery-card-selected', selectionMode && selectedAssetIds.has(id));
card.classList.toggle('media-gallery-card-selection-disabled', selectionMode && item.dataset.mediaUsed === 'true');
}
});
}
function clearSelectedAssets() {
selectedAssetIds.clear();
}
function setSelectionMode(enabled) {
selectionMode = Boolean(enabled);
if (!selectionMode) clearSelectedAssets();
if (gallery) gallery.classList.toggle('media-gallery-selection-mode', selectionMode);
updateBulkDeleteActions();
}
function submitBulkDelete() {
if (!selectedAssetIds.size || !window.confirm('Delete ' + selectedAssetIds.size + ' selected media asset' + (selectedAssetIds.size === 1 ? '' : 's') + '?')) {
return;
}
const form = document.createElement('form');
form.method = 'post';
form.action = '/media-library/delete';
selectedAssetIds.forEach(function (id) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'assetIds[]';
input.value = id;
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
}
async function refreshGallery() {
const requestSequence = ++galleryRefreshSequence;
try {
const response = await fetch('/media-library/assets?' + getGalleryQuery(0, 4 * getColumnsPerRow()), { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error('Unable to refresh media.');
const result = await response.json();
if (requestSequence !== galleryRefreshSequence) return;
galleryItems.forEach(function (item) { item.remove(); });
galleryItems = [];
clearSelectedAssets();
(result.assets || []).forEach(appendGalleryAsset);
galleryOffset = Number(result.nextOffset || 0);
galleryHasMore = Boolean(result.hasMore);
galleryTotal = Number(result.total || 0);
visibleRowLimit = 4;
updateSearchResults();
} catch (error) {
showUploadMessage(error.message || 'Unable to refresh media.');
}
}
function resetVisibleItemLimit() {
visibleRowLimit = 4;
refreshGallery();
}
if (search) {
search.addEventListener('input', resetVisibleItemLimit);
}
if (typeFilter) typeFilter.addEventListener('change', resetVisibleItemLimit);
if (usageFilter) usageFilter.addEventListener('change', resetVisibleItemLimit);
if (sort) sort.addEventListener('change', resetVisibleItemLimit);
if (gallery) {
gallery.addEventListener('click', function (event) {
if (!selectionMode) return;
const column = event.target && event.target.closest ? event.target.closest('[data-media-gallery-column]') : null;
if (!column || !gallery.contains(column)) return;
event.preventDefault();
event.stopPropagation();
if (column.dataset.mediaUsed === 'true') {
showUploadMessage('This media is in use and cannot be selected.');
return;
}
const id = String(column.dataset.mediaId || '');
if (!id) return;
if (selectedAssetIds.has(id)) selectedAssetIds.delete(id);
else selectedAssetIds.add(id);
updateBulkDeleteActions();
});
}
if (selectModeButton) selectModeButton.addEventListener('click', function () { setSelectionMode(!selectionMode); });
if (deleteSelectedButton) deleteSelectedButton.addEventListener('click', submitBulkDelete);
if (loadMoreButton) {
loadMoreButton.addEventListener('click', async function () {
loadMoreButton.disabled = true;
try {
const response = await fetch('/media-library/assets?' + getGalleryQuery(galleryOffset, 4 * getColumnsPerRow()), { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error('Unable to load more media.');
const result = await response.json();
(result.assets || []).forEach(appendGalleryAsset);
galleryOffset = Number(result.nextOffset || galleryOffset);
galleryHasMore = Boolean(result.hasMore);
galleryTotal = Number(result.total || galleryTotal);
visibleRowLimit += 4;
updateSearchResults();
} catch (error) {
showUploadMessage(error.message || 'Unable to load more media.');
} finally {
loadMoreButton.disabled = false;
}
});
}
updateSearchResults();
function showPreviewModal() {
if (window.pulseModal && typeof window.pulseModal.show === 'function') {
window.pulseModal.show(modal);
} else if (window.bootstrap && window.bootstrap.Modal) {
window.bootstrap.Modal.getOrCreateInstance(modal).show();
}
}
if (modal && body) {
document.addEventListener('click', function (event) {
const preview = event.target && event.target.closest ? event.target.closest('[data-media-gallery-preview]') : null;
if (!preview) {
return;
}
const path = preview.getAttribute('data-media-path') || '';
const type = preview.getAttribute('data-media-type') || 'image';
const name = preview.getAttribute('data-media-name') || 'Media preview';
body.replaceChildren();
if (title) {
title.textContent = name;
}
const media = document.createElement(type === 'video' ? 'video' : 'img');
media.src = path;
media.alt = type === 'video' ? '' : name;
if (type === 'video') {
media.controls = true;
media.playsInline = true;
}
body.appendChild(media);
showPreviewModal();
});
modal.addEventListener('hidden.bs.modal', function () {
body.replaceChildren();
});
}
+102
View File
@@ -384,9 +384,111 @@
setActiveSection(initialSection); setActiveSection(initialSection);
} }
function initEmailTemplatePreviews() {
var previewUser = document.querySelector('[data-email-preview-user]');
var signedInUser = {
username: previewUser ? previewUser.getAttribute('data-username') : '',
display_name: previewUser ? previewUser.getAttribute('data-display-name') : '',
email: previewUser ? previewUser.getAttribute('data-email') : '',
verification_expiry: previewUser ? previewUser.getAttribute('data-verification-expiry') : '30',
reset_expiry: previewUser ? previewUser.getAttribute('data-reset-expiry') : '30',
invitation_expiry: previewUser ? previewUser.getAttribute('data-invitation-expiry') : '24'
};
document.querySelectorAll('[data-email-template-editor]').forEach(function (editor) {
var subject = editor.querySelector('[data-email-template-subject]');
var body = editor.querySelector('[data-email-template-body]');
var alignment = editor.querySelector('[data-email-template-alignment]');
var buttonText = editor.querySelector('[data-email-template-button-text]');
var preview = editor.querySelector('[data-email-template-preview]');
if (!subject || !body || !preview) return;
var isVerificationTemplate = Boolean(editor.querySelector('[name="verification_subject"]'));
var isResetTemplate = Boolean(editor.querySelector('[name="reset_subject"]'));
var isInvitationTemplate = Boolean(editor.querySelector('[name="invitation_subject"]'));
function render() {
preview.innerHTML = '';
var shell = document.createElement('div');
shell.className = 'email-template-preview__shell';
var brand = document.createElement('div');
brand.className = 'email-template-preview__brand';
brand.textContent = 'Pulse Signage';
var message = document.createElement('div');
message.className = 'email-template-preview__message';
var sampleValues = {
username: signedInUser.username || 'username',
display_name: signedInUser.display_name || signedInUser.username || 'Your name',
email: signedInUser.email || 'your-email@example.com',
expiry_time: isInvitationTemplate ? signedInUser.invitation_expiry + ' hours' : (isResetTemplate ? signedInUser.reset_expiry : signedInUser.verification_expiry) + ' minutes'
};
var button = document.createElement('div');
button.className = 'email-template-preview__button';
var buttonAlignment = alignment ? alignment.value : 'center';
var buttonWrap = document.createElement('div');
buttonWrap.className = 'email-template-preview__button-wrap';
buttonWrap.style.textAlign = buttonAlignment;
buttonWrap.appendChild(button);
var previewActionPlaceholder = '[[url]]';
button.textContent = buttonText && buttonText.value ? buttonText.value : (isVerificationTemplate ? 'Verify email address' : (isInvitationTemplate ? 'Accept invitation' : 'Reset password'));
var previewOrigin = window.location.origin || 'https://pulse-signage.example';
var previewVerificationUrl = previewOrigin + '/verify-email?token=preview-token';
var previewResetUrl = previewOrigin + '/reset-password?token=preview-token';
var previewActionUrl = isVerificationTemplate ? previewVerificationUrl : (isInvitationTemplate ? previewOrigin + '/accept-invite?token=preview-token' : previewResetUrl);
var hasExplicitButton = body.value.indexOf('[[action_button]]') !== -1;
body.value.split(/\r?\n(?:[ \t]*\r?\n)+/).forEach(function (sourceParagraph) {
var line = sourceParagraph.replace(/\[\[(username|display_name|email|expiry_time)\]\]/g, function (_match, key) { return sampleValues[key]; }).replace(previewActionPlaceholder, previewActionUrl);
var hasButtonToken = sourceParagraph.indexOf('[[action_button]]') !== -1;
var hasUrlToken = !hasExplicitButton && sourceParagraph.indexOf(previewActionPlaceholder) !== -1;
if (hasButtonToken) {
var buttonParts = line.split('[[action_button]]');
if (buttonParts[0]) appendPreviewParagraph(buttonParts[0]);
message.appendChild(buttonWrap);
if (buttonParts[1]) appendPreviewParagraph(buttonParts[1]);
return;
}
if (hasUrlToken) {
var legacyParts = sourceParagraph.split(previewActionPlaceholder);
if (legacyParts[0]) appendPreviewParagraph(legacyParts[0]);
message.appendChild(buttonWrap);
appendPreviewParagraph(previewActionUrl + legacyParts[1]);
return;
}
appendPreviewParagraph(line);
});
function appendPreviewParagraph(line) {
var paragraph = document.createElement('p');
paragraph.innerHTML = (line || '\u00a0').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r?\n/g, '<br>').replace(/(https?:\/\/[^\s<]+)/g, '<a href="$1">$1</a>').replace(/\[b\]([\s\S]*?)\[\/b\]/gi, '<strong>$1</strong>').replace(/\[i\]([\s\S]*?)\[\/i\]/gi, '<em>$1</em>').replace(/\[u\]([\s\S]*?)\[\/u\]/gi, '<u>$1</u>');
message.appendChild(paragraph);
}
preview.appendChild(brand);
shell.appendChild(message);
preview.appendChild(shell);
}
subject.addEventListener('input', render);
body.addEventListener('input', render);
if (alignment) alignment.addEventListener('change', render);
if (buttonText) buttonText.addEventListener('input', render);
editor.querySelectorAll('[data-email-format]').forEach(function (formatButton) {
formatButton.addEventListener('click', function () {
var tag = formatButton.getAttribute('data-email-format');
var start = body.selectionStart;
var end = body.selectionEnd;
var selected = body.value.slice(start, end) || 'text';
var markerPattern = new RegExp('^\\[' + tag + '\\]([\\s\\S]*)\\[\\/' + tag + '\\]$');
var replacement = markerPattern.test(selected) ? markerPattern.exec(selected)[1] : '[' + tag + ']' + selected + '[/' + tag + ']';
body.setRangeText(replacement, start, end, 'select');
body.dispatchEvent(new Event('input', { bubbles: true }));
body.focus();
});
});
render();
});
}
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function () {
initIconSuggestions(); initIconSuggestions();
initDefaultAnnouncementIconPicker(); initDefaultAnnouncementIconPicker();
initSettingsSectionNavigation(); initSettingsSectionNavigation();
initEmailTemplatePreviews();
}); });
}()); }());
@@ -36,6 +36,11 @@
'</dl>'; '</dl>';
} }
function renderMathTransforms() {
return '<h3 class="fs-6 mt-4 fw-normal">Math transforms</h3>' +
'<p class="small">Use <code>add(number)</code>, <code>subtract(number)</code>, <code>multiply(number)</code>, or <code>divide(number)</code>, for example <code>{{amount.multiply(10)}}</code>. Transforms can be chained, such as <code>{{amount.add(3).multiply(10)}}</code>.</p>';
}
function renderDateFormatTokens() { function renderDateFormatTokens() {
return '<h3 class="fs-6 mt-4 fw-normal">Date format tokens</h3>' + return '<h3 class="fs-6 mt-4 fw-normal">Date format tokens</h3>' +
'<p class="small">Use the <code>format("...")</code> transform with these tokens. Text inside square brackets is treated as a literal.</p>' + '<p class="small">Use the <code>format("...")</code> transform with these tokens. Text inside square brackets is treated as a literal.</p>' +
@@ -61,6 +66,7 @@
escapeHtml: escapeHtml, escapeHtml: escapeHtml,
render: render, render: render,
renderTextTransforms: renderTextTransforms, renderTextTransforms: renderTextTransforms,
renderMathTransforms: renderMathTransforms,
renderDateFormatTokens: renderDateFormatTokens, renderDateFormatTokens: renderDateFormatTokens,
renderImageTransform: renderImageTransform renderImageTransform: renderImageTransform
}; };
+223 -7
View File
@@ -27,9 +27,30 @@
return current === undefined || current === null ? '' : current; return current === undefined || current === null ? '' : current;
} }
function splitExpressionSegments(value) {
var segments = [];
var current = '';
var depth = 0;
String(value || '').split('').forEach(function (character) {
if (character === '(') {
depth += 1;
} else if (character === ')' && depth > 0) {
depth -= 1;
}
if (character === '.' && depth === 0) {
segments.push(current);
current = '';
return;
}
current += character;
});
segments.push(current);
return segments;
}
function parsePlaceholderExpression(expression) { function parsePlaceholderExpression(expression) {
var raw = String(expression || '').trim(); var raw = String(expression || '').trim();
var segments = raw ? raw.split('.') : []; var segments = raw ? splitExpressionSegments(raw) : [];
var transforms = []; var transforms = [];
while (segments.length) { while (segments.length) {
@@ -57,13 +78,33 @@
if (!source) { if (!source) {
return []; return [];
} }
var args = [];
if ((source[0] === '"' && source[source.length - 1] === '"') || (source[0] === '\'' && source[source.length - 1] === '\'')) { var current = '';
return [source.slice(1, -1)]; var quote = '';
source.split('').forEach(function (character) {
if ((character === '"' || character === '\'') && (!quote || quote === character)) {
quote = quote ? '' : character;
current += character;
return;
}
if (character === ',' && !quote) {
if (current.trim()) {
args.push(current.trim());
}
current = '';
return;
}
current += character;
});
if (current.trim()) {
args.push(current.trim());
} }
return args.map(function (item) {
return source.split(',').map(function (item) { var normalized = String(item || '').trim();
return String(item || '').trim(); if ((normalized[0] === '"' && normalized[normalized.length - 1] === '"') || (normalized[0] === '\'' && normalized[normalized.length - 1] === '\'')) {
return normalized.slice(1, -1);
}
return normalized;
}).filter(Boolean); }).filter(Boolean);
} }
@@ -253,6 +294,26 @@
return resolveTimeZone((args && args[0]) || (options && options.timeZone) || ''); return resolveTimeZone((args && args[0]) || (options && options.timeZone) || '');
} }
function toNumericValue(value) {
if (value && typeof value === 'object') {
var numericKeys = ['value', 'amount', 'current', 'total', 'goal', 'raised'];
for (var keyIndex = 0; keyIndex < numericKeys.length; keyIndex += 1) {
var nestedValue = value[numericKeys[keyIndex]];
if (nestedValue !== undefined && nestedValue !== null && nestedValue !== value) {
var nestedNumber = toNumericValue(nestedValue);
if (Number.isFinite(nestedNumber)) {
return nestedNumber;
}
}
}
return NaN;
}
var normalized = String(value === undefined || value === null ? '' : value).replace(/[^0-9.eE+-]/g, '');
var number = Number(normalized);
return Number.isFinite(number) ? number : NaN;
}
function applyTransform(value, transform, options) { function applyTransform(value, transform, options) {
var text = String(value === undefined || value === null ? '' : value); var text = String(value === undefined || value === null ? '' : value);
var name = String(transform && transform.name || '').trim().toLowerCase(); var name = String(transform && transform.name || '').trim().toLowerCase();
@@ -284,6 +345,18 @@
return getTimeZoneLongName(getTransformTimeZone(args, options)); return getTimeZoneLongName(getTransformTimeZone(args, options));
} }
if (name === 'add' || name === 'subtract' || name === 'multiply' || name === 'divide') {
var arithmeticValue = toNumericValue(value);
var operand = toNumericValue(args[0]);
if (!Number.isFinite(arithmeticValue) || !Number.isFinite(operand) || (name === 'divide' && operand === 0)) {
return value;
}
if (name === 'add') return arithmeticValue + operand;
if (name === 'subtract') return arithmeticValue - operand;
if (name === 'multiply') return arithmeticValue * operand;
return arithmeticValue / operand;
}
return text; return text;
} }
@@ -319,6 +392,147 @@
}; };
} }
function isProgressPlaceholderExpression(expression) {
var parsed = parsePlaceholderExpression(expression);
return parsed.transforms.some(function (transform) {
return transform && transform.name === 'progress';
});
}
function renderProgressPlaceholder(value, expression) {
var parsed = parsePlaceholderExpression(expression);
var transform = parsed.transforms.find(function (candidate) {
return candidate && candidate.name === 'progress';
});
if (!transform || !value || typeof value !== 'object' || transform.args.length < 2) {
return '';
}
function toNumber(raw) {
if (raw && typeof raw === 'object') {
var numericKeys = ['value', 'amount', 'current', 'total', 'goal', 'raised'];
for (var keyIndex = 0; keyIndex < numericKeys.length; keyIndex += 1) {
var nestedValue = raw[numericKeys[keyIndex]];
if (nestedValue !== undefined && nestedValue !== null && nestedValue !== raw) {
var nestedNumber = toNumber(nestedValue);
if (Number.isFinite(nestedNumber)) {
return nestedNumber;
}
}
}
return 0;
}
var normalized = String(raw === undefined || raw === null ? '' : raw).replace(/[^0-9.eE+-]/g, '');
var number = Number(normalized);
return Number.isFinite(number) ? number : 0;
}
function resolveProgressValue(argument) {
var raw = String(argument === undefined || argument === null ? '' : argument).trim();
var literal = raw.replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, '$1$2');
if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(literal)) {
return literal;
}
return resolvePath(value, raw);
}
var startValue = resolveProgressValue(transform.args[0]);
var endValue = resolveProgressValue(transform.args[1]);
var startDate = startValue instanceof Date ? startValue : new Date(startValue);
var endDate = endValue instanceof Date ? endValue : new Date(endValue);
var percentage;
if (typeof startValue === 'string' && typeof endValue === 'string' && /[-T]/.test(startValue) && /[-T]/.test(endValue) && !Number.isNaN(startDate.getTime()) && !Number.isNaN(endDate.getTime()) && endDate.getTime() > startDate.getTime()) {
percentage = Math.max(0, Math.min(100, ((Date.now() - startDate.getTime()) / (endDate.getTime() - startDate.getTime())) * 100));
} else {
var current = toNumber(startValue);
var goal = toNumber(endValue);
percentage = goal > 0 ? Math.max(0, Math.min(100, (current / goal) * 100)) : 0;
}
var roundedPercentage = Math.round(percentage * 10) / 10;
var label = roundedPercentage + '%';
var variants = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'];
var variantColors = {
primary: '#0d6efd',
secondary: '#6c757d',
success: '#198754',
danger: '#dc3545',
warning: '#ffc107',
info: '#0dcaf0',
light: '#f8f9fa',
dark: '#212529'
};
var announcementColors = {
orange: '#c84e10',
amber: '#a56710',
olive: '#5f7f0f',
teal: '#12827d',
sky: '#127caf',
indigo: '#6f60ea',
violet: '#9553db',
fuchsia: '#b347be',
pink: '#cd388d',
navy: '#1d2d4c',
steel: '#3a4860',
slate: '#566577',
graphite: '#32363c',
midnight: '#1e1d2d'
};
var variant = 'primary';
var barVariant = '';
var customColor = '';
var backgroundColor = '';
var colorCount = 0;
var modifiers = [];
var textless = false;
var borderRadius = 'var(--bs-border-radius)';
transform.args.slice(2).forEach(function (argument) {
var option = String(argument || '').trim().toLowerCase();
var isNamedColor = variants.indexOf(option) !== -1 || Object.prototype.hasOwnProperty.call(announcementColors, option);
var isHexColor = /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(option);
if (isNamedColor || isHexColor) {
var color = isHexColor ? option : (variantColors[option] || announcementColors[option]);
if (colorCount === 0) {
if (variants.indexOf(option) !== -1) {
variant = option;
barVariant = option;
}
customColor = color;
} else if (colorCount === 1) {
backgroundColor = color;
}
colorCount += 1;
}
if (option === 'striped' || option === 'animated') {
modifiers.push('progress-bar-' + option);
}
if (option === 'textless') {
textless = true;
}
if (option === 'square') {
borderRadius = '0';
} else if (option === 'pill') {
borderRadius = '50rem';
} else if (option === 'rounded') {
borderRadius = 'var(--bs-border-radius)';
} else {
var radiusMatch = option.match(/^radius\((0|[0-9]+(?:\.[0-9]+)?(?:px|rem|em|%)?)\)$/);
if (radiusMatch) {
borderRadius = radiusMatch[1];
}
}
});
var progressClass = 'progress';
var barClass = 'progress-bar' + (barVariant ? ' bg-' + barVariant : '') + (modifiers.length ? ' ' + modifiers.join(' ') : '');
var barStyle = 'width:' + roundedPercentage + '%;color:inherit;';
if (customColor) {
barStyle += 'background-color:' + customColor + ';';
}
var progressStyleValue = (backgroundColor ? 'background-color:' + backgroundColor + ';' : '') + 'font-size:inherit;--bs-progress-font-size:inherit;--bs-progress-height:1em;height:1em;border-radius:' + borderRadius + ';';
var progressStyle = progressStyleValue ? ' style="' + progressStyleValue + '"' : '';
return '<span class="' + progressClass + ' api-progress"' + progressStyle + ' role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + roundedPercentage + '" aria-label="' + label + '">' +
'<span class="' + barClass + '" style="' + barStyle + '">' + (textless ? '' : label) + '</span></span>';
}
function formatPlaceholderValue(value) { function formatPlaceholderValue(value) {
if (value === undefined || value === null) { if (value === undefined || value === null) {
return ''; return '';
@@ -372,6 +586,8 @@
resolvePlaceholderExpression: resolvePlaceholderExpression, resolvePlaceholderExpression: resolvePlaceholderExpression,
isImagePlaceholderExpression: isImagePlaceholderExpression, isImagePlaceholderExpression: isImagePlaceholderExpression,
getImagePlaceholderConfig: getImagePlaceholderConfig, getImagePlaceholderConfig: getImagePlaceholderConfig,
isProgressPlaceholderExpression: isProgressPlaceholderExpression,
renderProgressPlaceholder: renderProgressPlaceholder,
formatPlaceholderValue: formatPlaceholderValue, formatPlaceholderValue: formatPlaceholderValue,
collectPlaceholderFieldPaths: collectPlaceholderFieldPaths collectPlaceholderFieldPaths: collectPlaceholderFieldPaths
}; };
@@ -187,7 +187,7 @@ export function createSlideFormPreviewHelpers(options) {
} }
var raw = String(rawValue || ''); var raw = String(rawValue || '');
if (!raw) { if (!raw) {
return '<div class="slide-preview-placeholder">Empty text</div>'; return '';
} }
return sanitizePreviewHtml(raw); return sanitizePreviewHtml(raw);
} }
@@ -10,6 +10,7 @@ export function createSlideFormRegionHelpers(options) {
var apiSources = Array.isArray(settings.apiSources) ? settings.apiSources : []; var apiSources = Array.isArray(settings.apiSources) ? settings.apiSources : [];
var timetableGroups = Array.isArray(settings.timetableGroups) ? settings.timetableGroups : []; var timetableGroups = Array.isArray(settings.timetableGroups) ? settings.timetableGroups : [];
var weatherLocations = Array.isArray(settings.weatherLocations) ? settings.weatherLocations : []; var weatherLocations = Array.isArray(settings.weatherLocations) ? settings.weatherLocations : [];
var mediaAssets = Array.isArray(settings.mediaAssets) ? settings.mediaAssets : [];
var getRegionTypeModule = typeof settings.getRegionTypeModule === 'function' ? settings.getRegionTypeModule : function () { return null; }; var getRegionTypeModule = typeof settings.getRegionTypeModule === 'function' ? settings.getRegionTypeModule : function () { return null; };
var requestPreviewRender = typeof settings.requestPreviewRender === 'function' ? settings.requestPreviewRender : function () {}; var requestPreviewRender = typeof settings.requestPreviewRender === 'function' ? settings.requestPreviewRender : function () {};
var placeholderUtils = window.placeholderUtils || {}; var placeholderUtils = window.placeholderUtils || {};
@@ -138,7 +139,7 @@ export function createSlideFormRegionHelpers(options) {
? placeholderChips.renderChip(field) ? placeholderChips.renderChip(field)
: '<span class="chip">{{' + escapeHtml(field) + '}}</span>'; : '<span class="chip">{{' + escapeHtml(field) + '}}</span>';
}).join(''); }).join('');
var transformHint = includeTransformHint === false ? '' : '<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>, <code>{{publishedAt.format("MMM D, YYYY")}}</code>.</div>'; var transformHint = includeTransformHint === false ? '' : '<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>, <code>{{publishedAt.format("MMM D, YYYY")}}</code>, or <code>{{amount.multiply(10)}}</code>.</div>';
if (!overflowFields.length) { if (!overflowFields.length) {
return visibleMarkup + transformHint; return visibleMarkup + transformHint;
@@ -322,7 +323,7 @@ export function createSlideFormRegionHelpers(options) {
} }
if (!item || typeof item !== 'object') { if (!item || typeof item !== 'object') {
return '<div class="slide-preview-placeholder">RSS item</div>'; return '';
} }
var title = String(item.title || '').trim(); var title = String(item.title || '').trim();
@@ -335,7 +336,7 @@ export function createSlideFormRegionHelpers(options) {
summary.push('<p>' + sanitizePreviewHtml(description) + '</p>'); summary.push('<p>' + sanitizePreviewHtml(description) + '</p>');
} }
if (!summary.length) { if (!summary.length) {
return '<div class="slide-preview-placeholder">RSS item</div>'; return '';
} }
return summary.join(''); return summary.join('');
} }
@@ -570,7 +571,8 @@ export function createSlideFormRegionHelpers(options) {
: [], : [],
sampleDataPreview: buildApiSampleDataMarkup(getCurrentApiConfig(region).source_id, getCurrentApiConfig(region).item_number, getCurrentApiConfig(region).items_path), sampleDataPreview: buildApiSampleDataMarkup(getCurrentApiConfig(region).source_id, getCurrentApiConfig(region).item_number, getCurrentApiConfig(region).items_path),
timetableGroups: timetableGroups, timetableGroups: timetableGroups,
weatherLocations: weatherLocations weatherLocations: weatherLocations,
mediaAssets: mediaAssets
}, existingContent, region.region_type === 'rss' ? rssFeeds : region.region_type === 'timetable' ? timetableGroups : region.region_type === 'weather' ? weatherLocations : apiSources); }, existingContent, region.region_type === 'rss' ? rssFeeds : region.region_type === 'timetable' ? timetableGroups : region.region_type === 'weather' ? weatherLocations : apiSources);
} }
@@ -612,7 +614,8 @@ export function createSlideFormRegionHelpers(options) {
: [], : [],
sampleDataPreview: buildApiSampleDataMarkup(apiConfig.source_id, apiConfig.item_number, apiItemsPath), sampleDataPreview: buildApiSampleDataMarkup(apiConfig.source_id, apiConfig.item_number, apiItemsPath),
timetableGroups: timetableGroups, timetableGroups: timetableGroups,
weatherLocations: weatherLocations weatherLocations: weatherLocations,
mediaAssets: mediaAssets
}; };
} }
+2 -1
View File
@@ -169,6 +169,7 @@ import { createSlideFormPreviewHelpers } from '/assets/js/slides/slide-form-prev
apiSources: apiSources, apiSources: apiSources,
timetableGroups: timetableGroups, timetableGroups: timetableGroups,
weatherLocations: weatherLocations, weatherLocations: weatherLocations,
mediaAssets: Array.isArray(slideEditorData.mediaAssets) ? slideEditorData.mediaAssets : [],
defaultFontSize: DEFAULT_FONT_SIZE, defaultFontSize: DEFAULT_FONT_SIZE,
uploadMaxLabel: uploadMaxLabel, uploadMaxLabel: uploadMaxLabel,
uploadVideoMaxLabel: uploadVideoMaxLabel, uploadVideoMaxLabel: uploadVideoMaxLabel,
@@ -927,7 +928,7 @@ import { createSlideFormPreviewHelpers } from '/assets/js/slides/slide-form-prev
} }
templateSelect.addEventListener('change', renderTemplate); templateSelect.addEventListener('change', renderTemplate);
templateFields.addEventListener('change', function () { templateFields.addEventListener('change', function (event) {
var webpageInput = event.target && typeof event.target.matches === 'function' && event.target.matches('input[type="url"][name^="region_webpage_"]'); var webpageInput = event.target && typeof event.target.matches === 'function' && event.target.matches('input[type="url"][name^="region_webpage_"]');
if (webpageInput) { if (webpageInput) {
templateSelectorLock.arm(); templateSelectorLock.arm();
+20
View File
@@ -129,6 +129,26 @@
input.value = String(currentUrl.searchParams.get(searchParam) || '').trim(); input.value = String(currentUrl.searchParams.get(searchParam) || '').trim();
var searchGroup = input.closest('.table-search-group');
if (searchGroup) {
var actionButton = searchGroup.parentNode ? searchGroup.parentNode.querySelector('.btn:not(.table-search-group .btn)') : null;
if (actionButton && actionButton.getBoundingClientRect) {
searchGroup.style.setProperty('--table-search-action-offset', (actionButton.getBoundingClientRect().width + 8) + 'px');
}
var searchToggle = searchGroup.querySelector('[data-table-search-toggle]');
if (searchToggle) {
searchToggle.addEventListener('click', function () {
focusSearchInput(input);
});
searchToggle.addEventListener('keydown', function (event) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
focusSearchInput(input);
}
});
}
}
function updateSearch() { function updateSearch() {
var query = String(input.value || '').trim(); var query = String(input.value || '').trim();
var nextUrl = new URL(window.location.href); var nextUrl = new URL(window.location.href);
@@ -1776,19 +1776,28 @@
renderAddRegionOptions(); renderAddRegionOptions();
} }
backgroundInput.addEventListener('change', function () { if (backgroundInput) {
var file = backgroundInput.files && backgroundInput.files[0]; backgroundInput.addEventListener('change', function () {
if (file) { var file = backgroundInput.files && backgroundInput.files[0];
updateBackgroundPreview(file); if (file) {
} updateBackgroundPreview(file);
}); }
});
}
if (removeBackgroundButton && removeBackgroundFlag) { if (removeBackgroundButton && removeBackgroundFlag) {
removeBackgroundButton.addEventListener('click', function () { removeBackgroundButton.addEventListener('click', function () {
removeBackgroundFlag.checked = true; removeBackgroundFlag.checked = true;
backgroundInput.value = ''; var backgroundPathInput = document.getElementById('existing-background-image-path');
if (backgroundPathInput) {
backgroundPathInput.value = '';
backgroundPathInput.dispatchEvent(new Event('change', { bubbles: true }));
}
if (backgroundInput) {
backgroundInput.value = '';
}
backgroundPreview.removeAttribute('src'); backgroundPreview.removeAttribute('src');
backgroundPreview.style.display = 'none'; backgroundPreview.style.display = 'none';
backgroundEmpty.style.display = 'block'; backgroundEmpty.style.display = 'flex';
}); });
} }
if (animationAdvancedModal) { if (animationAdvancedModal) {
+7 -2
View File
@@ -33,17 +33,22 @@ module.exports = function renderAccountPage(currentUser, message, returnUrl, all
? 'Use at least ' + requirements.minimumLength + ' characters and include uppercase, lowercase, number, and symbol.' ? 'Use at least ' + requirements.minimumLength + ' characters and include uppercase, lowercase, number, and symbol.'
: 'Use at least ' + requirements.minimumLength + ' characters and include ' + requirements.minimumCategories + ' of: uppercase, lowercase, number, and symbol.'; : 'Use at least ' + requirements.minimumLength + ' characters and include ' + requirements.minimumCategories + ' of: uppercase, lowercase, number, and symbol.';
return renderView('account/password', { return renderView('account/index', {
title: 'My account', title: 'My account',
active: 'account', active: 'account',
currentUser: currentUser || null, currentUser: currentUser || null,
message: message || '', message: message || '',
username: currentUser ? currentUser.username : '', username: currentUser ? currentUser.username : '',
name: currentUser ? String(currentUser.name || '') : '', name: currentUser ? String(currentUser.name || '') : '',
email: currentUser ? String(currentUser.email || '') : '',
emailPending: Boolean(currentUser && currentUser.pending_email),
pendingEmail: currentUser ? String(currentUser.pending_email || '') : '',
emailVerified: Boolean(currentUser && currentUser.email_verified_at),
returnUrl: normalizeReturnUrl(returnUrl), returnUrl: normalizeReturnUrl(returnUrl),
allowUserSessionRevocation: Boolean(allowUserSessionRevocation), allowUserSessionRevocation: Boolean(allowUserSessionRevocation),
sessions: Array.isArray(sessions) ? sessions : [], sessions: Array.isArray(sessions) ? sessions : [],
passwordMinimumLength: requirements.minimumLength, passwordMinimumLength: requirements.minimumLength,
passwordRequirementsText: passwordRequirementsText passwordRequirementsText: passwordRequirementsText,
scripts: ['js/account/account-page.js']
}); });
}; };
+96 -1
View File
@@ -1,6 +1,8 @@
// Admin account route registration and profile helpers. // Admin account route registration and profile helpers.
const { fetchAppSettings } = require('#src/data/app-settings'); const { fetchAppSettings } = require('#src/data/app-settings');
const { formatAccountEmailExpiry, renderAccountEmailTemplate } = require('#src/data/account-email-templates');
const { formatUserAgentLabel } = require('#src/data/audit-log');
module.exports = function registerAccountRoutes(app, deps) { module.exports = function registerAccountRoutes(app, deps) {
const pool = deps.pool; const pool = deps.pool;
@@ -18,6 +20,8 @@ module.exports = function registerAccountRoutes(app, deps) {
const hashSessionToken = deps.hashSessionToken; const hashSessionToken = deps.hashSessionToken;
const sessionCookieName = deps.sessionCookieName; const sessionCookieName = deps.sessionCookieName;
const recordRequestAuditEvent = deps.recordRequestAuditEvent; const recordRequestAuditEvent = deps.recordRequestAuditEvent;
const sendAccountEmail = deps.sendAccountEmail;
const createOneTimeToken = deps.createOneTimeToken;
async function getPasswordRequirements() { async function getPasswordRequirements() {
const settings = await fetchAppSettings(pool); const settings = await fetchAppSettings(pool);
@@ -43,6 +47,30 @@ module.exports = function registerAccountRoutes(app, deps) {
}; };
} }
function getRequestOrigin(req) {
const forwardedProto = String(req.headers['x-forwarded-proto'] || req.protocol || 'http').split(',')[0].trim();
const forwardedHost = String(req.headers['x-forwarded-host'] || req.headers.host || '').split(',')[0].trim();
return forwardedHost ? forwardedProto + '://' + forwardedHost : '';
}
app.post('/account/email', async function (req, res, next) {
try {
const email = String(req.body.email || '').trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return res.status(400).send('Email address is invalid.');
const settings = await fetchAppSettings(pool);
if (!settings['email.smtp_enabled'] || typeof sendAccountEmail !== 'function') return res.status(400).send('Email delivery is not configured.');
const token = createOneTimeToken();
const expiryMinutes = Number(settings['email.verification_expiry_minutes']);
await pool.query('UPDATE a_users SET pending_email = ?, pending_email_token_hash = ?, pending_email_expires_at = DATE_ADD(NOW(), INTERVAL ' + expiryMinutes + ' MINUTE) WHERE id = ?', [email, hashSessionToken(token), req.currentUser.id]);
const url = getRequestOrigin(req) + '/verify-email?token=' + encodeURIComponent(token);
await sendAccountEmail(settings, Object.assign({ to: email }, renderAccountEmailTemplate(settings['email.verification_subject'], settings['email.verification_body'], { url: url, username: req.currentUser.username, display_name: req.currentUser.name, email: email, expiry_time: formatAccountEmailExpiry(expiryMinutes, 'minutes'), action_alignment: settings['email.verification_button_alignment'], action_label: settings['email.verification_button_text'] })));
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.email_change_requested', actorUserId: req.currentUser.id, targetType: 'user', targetId: req.currentUser.id, targetLabel: email });
res.redirect('/account?message=' + encodeURIComponent('Check your new email address for a verification link.'));
} catch (error) {
next(error);
}
});
app.get('/account', function (req, res) { app.get('/account', function (req, res) {
fetchAppSettings(pool).then(function (settings) { fetchAppSettings(pool).then(function (settings) {
const passwordRequirements = buildPasswordRequirements(settings); const passwordRequirements = buildPasswordRequirements(settings);
@@ -61,7 +89,7 @@ module.exports = function registerAccountRoutes(app, deps) {
id: Number(session.id), id: Number(session.id),
isCurrent: Boolean(tokenHash && session.session_hash === tokenHash), isCurrent: Boolean(tokenHash && session.session_hash === tokenHash),
ipAddress: String(session.ip_address || 'Unknown'), ipAddress: String(session.ip_address || 'Unknown'),
userAgent: String(session.user_agent || 'Unknown browser'), userAgent: formatUserAgentLabel(session.user_agent) || 'Unknown browser',
createdAtLabel: formatDashboardDate(session.created_at), createdAtLabel: formatDashboardDate(session.created_at),
lastUsedAtLabel: formatDashboardDate(session.last_used_at), lastUsedAtLabel: formatDashboardDate(session.last_used_at),
expiresAtLabel: formatDashboardDate(session.expires_at) expiresAtLabel: formatDashboardDate(session.expires_at)
@@ -74,6 +102,53 @@ module.exports = function registerAccountRoutes(app, deps) {
}); });
}); });
app.post('/account/profile', async function (req, res, next) {
try {
const name = String(req.body.name || '').trim();
const username = common.validateMaxLength(req.body.username || '', 64, 'Username');
const email = String(req.body.email || '').trim().toLowerCase();
const currentPassword = String(req.body.current_password || '');
if (!name) return res.status(400).send('Name is required.');
if (!username) return res.status(400).send('Username is required.');
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return res.status(400).send('Email address is invalid.');
if (!currentPassword) return res.status(400).send('Current password is required.');
const [rows] = await pool.query('SELECT id, username, name, email, password_hash, password_salt, password_iterations FROM a_users WHERE id = ? LIMIT 1', [req.currentUser.id]);
const user = rows[0] || null;
if (!user) return res.status(404).send('User not found.');
if (!verifyPassword(currentPassword, user)) return res.status(400).send('Current password is incorrect.');
if (username !== user.username && await common.fetchDuplicateName(pool, 'a_users', username, user.id, 'username')) return res.status(400).send('That username already exists.');
if (name !== user.name && await common.fetchDuplicateName(pool, 'a_users', name, user.id)) return res.status(400).send('That name already exists.');
const confirmedEmail = String(user.email || '').trim().toLowerCase();
const pendingEmail = String(user.pending_email || '').trim().toLowerCase();
const emailChanged = email !== confirmedEmail && email !== pendingEmail;
const pendingEmailCleared = Boolean(pendingEmail && email === confirmedEmail);
const settings = emailChanged ? await fetchAppSettings(pool) : null;
if (emailChanged && email && (!settings['email.smtp_enabled'] || typeof sendAccountEmail !== 'function')) return res.status(400).send('Email delivery is not configured.');
const actorId = getAuditUserId(req);
await pool.query('UPDATE a_users SET username = ?, name = ?, modified_by = ? WHERE id = ?', [username, name, actorId, user.id]);
if (emailChanged || pendingEmailCleared) {
if (!email) {
await pool.query('UPDATE a_users SET email = NULL, email_verified_at = NULL, pending_email = NULL, pending_email_token_hash = NULL, pending_email_expires_at = NULL WHERE id = ?', [user.id]);
} else if (pendingEmailCleared) {
await pool.query('UPDATE a_users SET pending_email = NULL, pending_email_token_hash = NULL, pending_email_expires_at = NULL WHERE id = ?', [user.id]);
} else {
const token = createOneTimeToken();
const expiryMinutes = Number(settings['email.verification_expiry_minutes']);
await pool.query('UPDATE a_users SET pending_email = ?, pending_email_token_hash = ?, pending_email_expires_at = DATE_ADD(NOW(), INTERVAL ' + expiryMinutes + ' MINUTE) WHERE id = ?', [email, hashSessionToken(token), user.id]);
const url = getRequestOrigin(req) + '/verify-email?token=' + encodeURIComponent(token);
await sendAccountEmail(settings, Object.assign({ to: email }, renderAccountEmailTemplate(settings['email.verification_subject'], settings['email.verification_body'], { url: url, username: req.currentUser.username, display_name: req.currentUser.name, email: email, expiry_time: formatAccountEmailExpiry(expiryMinutes, 'minutes'), action_alignment: settings['email.verification_button_alignment'], action_label: settings['email.verification_button_text'] })));
}
}
if (emailChanged && typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: email ? 'user.email_change_requested' : 'user.email_cleared', actorUserId: user.id, targetType: 'user', targetId: user.id, targetLabel: email || user.email, details: { previousEmail: confirmedEmail || null, email: email || null, verificationRequired: Boolean(email) } });
res.redirect('/account?message=' + encodeURIComponent(emailChanged && email ? 'Account details updated. Check your new email address for a verification link.' : 'Account details updated.'));
} catch (error) {
next(error);
}
});
app.post('/account/sessions/:id/revoke', async function (req, res, next) { app.post('/account/sessions/:id/revoke', async function (req, res, next) {
try { try {
const sessionId = Number(req.params.id); const sessionId = Number(req.params.id);
@@ -161,6 +236,26 @@ module.exports = function registerAccountRoutes(app, deps) {
} }
}); });
app.post('/account/username', async function (req, res, next) {
try {
const username = common.validateMaxLength(req.body.username || '', 255, 'Username');
const currentPassword = String(req.body.current_password || '');
if (!username) return res.status(400).send('Username is required.');
if (!currentPassword) return res.status(400).send('Current password is required.');
const [rows] = await pool.query('SELECT id, username, password_hash, password_salt, password_iterations FROM a_users WHERE id = ? LIMIT 1', [req.currentUser.id]);
const user = rows[0] || null;
if (!user) return res.status(404).send('User not found.');
if (!verifyPassword(currentPassword, user)) return res.status(400).send('Current password is incorrect.');
const [existingRows] = await pool.query('SELECT id FROM a_users WHERE username = ? AND id <> ? LIMIT 1', [username, user.id]);
if (existingRows.length) return res.status(400).send('That username already exists.');
await pool.query('UPDATE a_users SET username = ?, modified_by = ? WHERE id = ?', [username, getAuditUserId(req), user.id]);
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.username_updated', actorUserId: user.id, targetType: 'user', targetId: user.id, targetLabel: username, details: { previousUsername: user.username, username: username } });
res.redirect('/account?message=' + encodeURIComponent('Username updated.'));
} catch (error) {
next(error);
}
});
app.post('/account/password', async function (req, res, next) { app.post('/account/password', async function (req, res, next) {
try { try {
const currentPassword = String(req.body.current_password || ''); const currentPassword = String(req.body.current_password || '');
+39
View File
@@ -14,6 +14,21 @@ module.exports = function registerScreenCommandRoutes(app, deps) {
const withClientNameReservation = deps.withClientNameReservation; const withClientNameReservation = deps.withClientNameReservation;
const broadcastDashboardState = deps.broadcastDashboardState; const broadcastDashboardState = deps.broadcastDashboardState;
const requirePermission = deps.requirePermission; const requirePermission = deps.requirePermission;
const recordRequestAuditEvent = deps.recordRequestAuditEvent;
async function recordScreenControlAudit(req, screenSlug, command, details) {
if (typeof recordRequestAuditEvent !== 'function') {
return;
}
await recordRequestAuditEvent(pool, req, {
category: 'screen-controls',
eventType: 'screen-control.' + command,
actorUserId: req.currentUser && req.currentUser.id,
targetType: screenSlug === '__all__' ? 'all-screens' : 'screen',
targetLabel: screenSlug === '__all__' ? 'All screens' : screenSlug,
details: details || {}
});
}
function normalizeExplicitPlayerBaseUrl(value) { function normalizeExplicitPlayerBaseUrl(value) {
return String(value || '').trim().replace(/\/$/, ''); return String(value || '').trim().replace(/\/$/, '');
@@ -250,6 +265,13 @@ module.exports = function registerScreenCommandRoutes(app, deps) {
await broadcastDashboardState(); await broadcastDashboardState();
} }
await recordScreenControlAudit(req, '__all__', command, {
targetScreenCount: targets.length,
targetPlayerCount: sentCount,
blackout: command === 'blackout' ? Boolean(commandPayload.blackout) : undefined,
paused: command === 'pause' ? Boolean(commandPayload.paused) : undefined
});
return res.json({ return res.json({
ok: true, ok: true,
allScreens: true, allScreens: true,
@@ -364,6 +386,8 @@ module.exports = function registerScreenCommandRoutes(app, deps) {
await broadcastDashboardState(); await broadcastDashboardState();
} }
await recordScreenControlAudit(req, slug, command, { clientName: selectedClientName, deviceId: deviceId });
return res.json({ return res.json({
screen: screenRows[0], screen: screenRows[0],
screenSlug: slug, screenSlug: slug,
@@ -386,6 +410,8 @@ module.exports = function registerScreenCommandRoutes(app, deps) {
return res.status(404).json({ error: 'Client not found' }); return res.status(404).json({ error: 'Client not found' });
} }
await recordScreenControlAudit(req, slug, command, { clientName: selectedClientName, deviceId: deviceId });
return res.json({ return res.json({
screen: screenRows[0], screen: screenRows[0],
screenSlug: slug, screenSlug: slug,
@@ -604,6 +630,13 @@ module.exports = function registerScreenCommandRoutes(app, deps) {
await broadcastDashboardState(); await broadcastDashboardState();
} }
await recordScreenControlAudit(req, slug, command, {
connectionId: connectionId || null,
deviceId: physicalPlayerId,
targetScreenSlug: targetScreenSlug,
clientName: status ? status.client_name : resolvedClientName
});
return res.json({ return res.json({
screen: screenRows[0], screen: screenRows[0],
screenSlug: slug, screenSlug: slug,
@@ -645,6 +678,12 @@ module.exports = function registerScreenCommandRoutes(app, deps) {
await broadcastDashboardState(); await broadcastDashboardState();
} }
await recordScreenControlAudit(req, slug, command, {
connectionId: connectionId || null,
blackout: command === 'blackout' ? Boolean(commandPayload.blackout) : undefined,
paused: command === 'pause' ? Boolean(commandPayload.paused) : undefined
});
return res.json(Object.assign({ return res.json(Object.assign({
screen: screenRows[0], screen: screenRows[0],
screenSlug: slug, screenSlug: slug,
+30 -3
View File
@@ -7,6 +7,7 @@ const { fetchAppSettings } = require('#src/data/app-settings');
const { convertWeatherSnapshot } = require('#src/data/weather-units'); const { convertWeatherSnapshot } = require('#src/data/weather-units');
const { buildAuditChanges } = require('#src/data/audit-log'); const { buildAuditChanges } = require('#src/data/audit-log');
const { PERMISSION_DENIED_MESSAGE } = require('#src/rbac'); const { PERMISSION_DENIED_MESSAGE } = require('#src/rbac');
const { fetchMediaAssets, registerMediaAssets, syncMediaAssetsFromDirectory, publishMediaAssets, removePendingMediaAssets } = require('#src/web/lib/media/library');
module.exports = function registerContentRoutes(app, deps) { module.exports = function registerContentRoutes(app, deps) {
const pool = deps.pool; const pool = deps.pool;
@@ -68,6 +69,8 @@ module.exports = function registerContentRoutes(app, deps) {
const timetableData = typeof common.fetchTimetablesData === 'function' ? await common.fetchTimetablesData(pool) : { timetableGroups: [] }; const timetableData = typeof common.fetchTimetablesData === 'function' ? await common.fetchTimetablesData(pool) : { timetableGroups: [] };
const weatherData = typeof common.fetchWeatherLocationsData === 'function' ? await common.fetchWeatherLocationsData(pool) : { weatherLocations: [] }; const weatherData = typeof common.fetchWeatherLocationsData === 'function' ? await common.fetchWeatherLocationsData(pool) : { weatherLocations: [] };
const appSettings = await fetchAppSettings(pool); const appSettings = await fetchAppSettings(pool);
await syncMediaAssetsFromDirectory(pool, deps.uploadDir);
const mediaAssets = (await fetchMediaAssets(pool)).slice(0, 24);
const apiSources = Array.isArray(apiData.apiSources) ? apiData.apiSources.map(function (source) { const apiSources = Array.isArray(apiData.apiSources) ? apiData.apiSources.map(function (source) {
return Object.assign({}, source, { return Object.assign({}, source, {
responseJson: typeof common.parseJsonSafe === 'function' ? common.parseJsonSafe(source.last_response_json) : null responseJson: typeof common.parseJsonSafe === 'function' ? common.parseJsonSafe(source.last_response_json) : null
@@ -92,6 +95,7 @@ module.exports = function registerContentRoutes(app, deps) {
apiSources: apiSources, apiSources: apiSources,
timetableGroups: timetableData.timetableGroups || [], timetableGroups: timetableData.timetableGroups || [],
weatherLocations: weatherLocations, weatherLocations: weatherLocations,
mediaAssets: mediaAssets,
fontLibrary: loadFontLibrary(deps.uploadDir), fontLibrary: loadFontLibrary(deps.uploadDir),
uploadLimits: { uploadLimits: {
imageMaxBytes: Number(appSettings['uploads.image_max_bytes']) || IMAGE_UPLOAD_MAX_BYTES, imageMaxBytes: Number(appSettings['uploads.image_max_bytes']) || IMAGE_UPLOAD_MAX_BYTES,
@@ -448,6 +452,9 @@ module.exports = function registerContentRoutes(app, deps) {
const uploadContext = String(req.get('X-Upload-Context') || req.query.context || '').trim().toLowerCase(); const uploadContext = String(req.get('X-Upload-Context') || req.query.context || '').trim().toLowerCase();
await validateUploadedFiles([req.file], uploadContext); await validateUploadedFiles([req.file], uploadContext);
await registerMediaAssets(pool, [req.file], function (file) {
return '/media/uploads/' + file.filename;
}, getUploadedFileMediaType, getAuditUserId(req), { published: false });
res.json({ res.json({
path: '/media/uploads/' + req.file.filename, path: '/media/uploads/' + req.file.filename,
@@ -471,7 +478,7 @@ module.exports = function registerContentRoutes(app, deps) {
return res.status(400).json({ error: 'No upload paths were provided.' }); return res.status(400).json({ error: 'No upload paths were provided.' });
} }
await removeUnusedUploadFiles(pool, deps.uploadDir, uploadPaths); await removePendingMediaAssets(pool, deps.uploadDir, uploadPaths);
res.sendStatus(204); res.sendStatus(204);
} catch (error) { } catch (error) {
next(error); next(error);
@@ -481,6 +488,9 @@ module.exports = function registerContentRoutes(app, deps) {
app.post('/slides', requirePermission('slides.create'), upload.any(), async function (req, res, next) { app.post('/slides', requirePermission('slides.create'), upload.any(), async function (req, res, next) {
try { try {
await validateUploadedFiles(req.files || []); await validateUploadedFiles(req.files || []);
await registerMediaAssets(pool, req.files, function (file) {
return '/media/uploads/' + file.filename;
}, getUploadedFileMediaType, getAuditUserId(req));
const payload = await common.buildSlidePayload(pool, req, null); const payload = await common.buildSlidePayload(pool, req, null);
if (await common.fetchDuplicateName(pool, 'c_slides', payload.title, null, 'title')) { if (await common.fetchDuplicateName(pool, 'c_slides', payload.title, null, 'title')) {
return res.status(400).send('A slide with that title already exists.'); return res.status(400).send('A slide with that title already exists.');
@@ -490,6 +500,7 @@ module.exports = function registerContentRoutes(app, deps) {
'INSERT INTO c_slides (title, template_id, content_json, created_by, modified_by) VALUES (?, ?, ?, ?, ?)', 'INSERT INTO c_slides (title, template_id, content_json, created_by, modified_by) VALUES (?, ?, ?, ?, ?)',
[payload.title, payload.templateId, payload.contentJson, actorId, actorId] [payload.title, payload.templateId, payload.contentJson, actorId, actorId]
); );
await publishMediaAssets(pool, collectUploadReferencesFromPayload(payload));
await syncPlaylistUploadsOnChange({ await syncPlaylistUploadsOnChange({
key: 'slide:create:' + result.insertId, key: 'slide:create:' + result.insertId,
pool: pool, pool: pool,
@@ -513,6 +524,9 @@ module.exports = function registerContentRoutes(app, deps) {
app.post('/slides/:id', requirePermission('slides.update'), upload.any(), async function (req, res, next) { app.post('/slides/:id', requirePermission('slides.update'), upload.any(), async function (req, res, next) {
try { try {
await validateUploadedFiles(req.files || []); await validateUploadedFiles(req.files || []);
await registerMediaAssets(pool, req.files, function (file) {
return '/media/uploads/' + file.filename;
}, getUploadedFileMediaType, getAuditUserId(req));
const slide = await common.fetchSlideById(pool, Number(req.params.id)); const slide = await common.fetchSlideById(pool, Number(req.params.id));
if (!slide) { if (!slide) {
return res.status(404).send('Slide not found'); return res.status(404).send('Slide not found');
@@ -539,6 +553,7 @@ module.exports = function registerContentRoutes(app, deps) {
'UPDATE c_slides SET title = ?, template_id = ?, content_json = ?, modified_by = ? WHERE id = ?', 'UPDATE c_slides SET title = ?, template_id = ?, content_json = ?, modified_by = ? WHERE id = ?',
[payload.title, payload.templateId, payload.contentJson, actorId, slide.id] [payload.title, payload.templateId, payload.contentJson, actorId, slide.id]
); );
await publishMediaAssets(pool, Array.from(new Set(Array.from(existingUploadRefs).concat(Array.from(nextUploadRefs)))));
await syncPlaylistUploadsOnChange({ await syncPlaylistUploadsOnChange({
key: 'slide:update:' + slide.id, key: 'slide:update:' + slide.id,
pool: pool, pool: pool,
@@ -615,7 +630,9 @@ module.exports = function registerContentRoutes(app, deps) {
app.get('/templates/new', requirePermission('templates.create'), async function (req, res, next) { app.get('/templates/new', requirePermission('templates.create'), async function (req, res, next) {
try { try {
const data = await common.fetchCanvasSizesData(pool); const data = await common.fetchCanvasSizesData(pool);
res.send(pages.renderTemplateAddPage(null, req.query.message ? String(req.query.message) : '', data.canvasSizes, req.currentUser)); await syncMediaAssetsFromDirectory(pool, deps.uploadDir);
const mediaAssets = (await fetchMediaAssets(pool)).slice(0, 24);
res.send(pages.renderTemplateAddPage(null, req.query.message ? String(req.query.message) : '', data.canvasSizes, req.currentUser, mediaAssets));
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -623,6 +640,10 @@ module.exports = function registerContentRoutes(app, deps) {
app.post('/templates', requirePermission('templates.create'), upload.any(), async function (req, res, next) { app.post('/templates', requirePermission('templates.create'), upload.any(), async function (req, res, next) {
try { try {
await validateUploadedFiles(req.files || []);
await registerMediaAssets(pool, req.files, function (file) {
return '/media/uploads/' + file.filename;
}, getUploadedFileMediaType, getAuditUserId(req));
const payload = await common.buildTemplatePayload(pool, req, null); const payload = await common.buildTemplatePayload(pool, req, null);
if (!payload.regions.length) { if (!payload.regions.length) {
return res.status(400).send('At least 1 region needs to be added.'); return res.status(400).send('At least 1 region needs to be added.');
@@ -668,7 +689,9 @@ module.exports = function registerContentRoutes(app, deps) {
template.region_usage = await fetchTemplateRegionUsage(template); template.region_usage = await fetchTemplateRegionUsage(template);
template.inUse = (await fetchSlidesByTemplateId(template.id)).length > 0; template.inUse = (await fetchSlidesByTemplateId(template.id)).length > 0;
const sizeData = await common.fetchCanvasSizesData(pool); const sizeData = await common.fetchCanvasSizesData(pool);
res.send(pages.renderTemplateEditPage(template, sizeData, req.query.message ? String(req.query.message) : '', req.currentUser)); await syncMediaAssetsFromDirectory(pool, deps.uploadDir);
const mediaAssets = await fetchMediaAssets(pool);
res.send(pages.renderTemplateEditPage(template, sizeData, req.query.message ? String(req.query.message) : '', req.currentUser, mediaAssets));
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -676,6 +699,10 @@ module.exports = function registerContentRoutes(app, deps) {
app.post('/templates/:id', requirePermission('templates.update'), upload.any(), async function (req, res, next) { app.post('/templates/:id', requirePermission('templates.update'), upload.any(), async function (req, res, next) {
try { try {
await validateUploadedFiles(req.files || []);
await registerMediaAssets(pool, req.files, function (file) {
return '/media/uploads/' + file.filename;
}, getUploadedFileMediaType, getAuditUserId(req));
const template = await common.fetchTemplateById(pool, Number(req.params.id)); const template = await common.fetchTemplateById(pool, Number(req.params.id));
if (!template) { if (!template) {
return res.status(404).send('Template not found'); return res.status(404).send('Template not found');
+175 -5
View File
@@ -1,7 +1,8 @@
// Admin user route registration and user-role management. // Admin user route registration and user-role management.
const { fetchAppSettings } = require('#src/data/app-settings'); const { fetchAppSettings } = require('#src/data/app-settings');
const { buildAuditChanges } = require('#src/data/audit-log'); const { formatAccountEmailExpiry, renderAccountEmailTemplate } = require('#src/data/account-email-templates');
const { buildAuditChanges, formatUserAgentLabel } = require('#src/data/audit-log');
module.exports = function registerUsersRoutes(app, deps) { module.exports = function registerUsersRoutes(app, deps) {
const pool = deps.pool; const pool = deps.pool;
@@ -10,6 +11,10 @@
const formatDashboardDate = deps.formatDashboardDate; const formatDashboardDate = deps.formatDashboardDate;
const getAuditUserId = deps.getAuditUserId; const getAuditUserId = deps.getAuditUserId;
const recordRequestAuditEvent = deps.recordRequestAuditEvent; const recordRequestAuditEvent = deps.recordRequestAuditEvent;
const sendAccountEmail = deps.sendAccountEmail;
const createOneTimeToken = deps.createOneTimeToken;
const hashSessionToken = deps.hashSessionToken;
const getRequestOrigin = deps.getRequestOrigin;
const hashPassword = deps.hashPassword; const hashPassword = deps.hashPassword;
const validatePasswordStrength = deps.validatePasswordStrength; const validatePasswordStrength = deps.validatePasswordStrength;
const readArrayField = deps.readArrayField; const readArrayField = deps.readArrayField;
@@ -20,6 +25,8 @@
const USER_NAME_MAX_LENGTH = 255; const USER_NAME_MAX_LENGTH = 255;
const USER_USERNAME_MAX_LENGTH = 255; const USER_USERNAME_MAX_LENGTH = 255;
const USER_EMAIL_MAX_LENGTH = 320;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const LIST_PAGE_SIZE = 25; const LIST_PAGE_SIZE = 25;
@@ -78,6 +85,23 @@
return { ok: true, roleIds: normalizedRoleIds }; return { ok: true, roleIds: normalizedRoleIds };
} }
function mapInvitationForView(invitation, roleNamesById) {
let roleIds = [];
try {
roleIds = JSON.parse(invitation.role_ids_json || '[]');
} catch (error) {
roleIds = [];
}
return Object.assign({}, invitation, {
roleNames: roleIds.map(function (roleId) {
return roleNamesById.get(Number(roleId));
}).filter(Boolean).join(', ') || 'No roles assigned',
createdAtLabel: formatDashboardDate(invitation.created_at),
expiresAtLabel: formatDashboardDate(invitation.expires_at),
createdByLabel: invitation.created_by_username || 'System'
});
}
app.get('/settings/users', requirePermission('users.read'), async function (req, res, next) { app.get('/settings/users', requirePermission('users.read'), async function (req, res, next) {
try { try {
const page = Math.max(1, Math.floor(Number(req.query.page) || 1)); const page = Math.max(1, Math.floor(Number(req.query.page) || 1));
@@ -102,6 +126,77 @@
} }
}); });
app.get('/settings/invitations', requirePermission('invitations.read'), async function (req, res, next) {
try {
const page = Math.max(1, Math.floor(Number(req.query.page) || 1));
const search = common.getSearchQuery(req);
const sort = common.getSortQuery(req);
const direction = common.getSortDirectionQuery(req);
const data = await rbacData.fetchInvitationsPage(pool, page, LIST_PAGE_SIZE, search, sort, direction);
const roles = await fetchRoleOptions();
const roleNamesById = new Map((roles || []).map(function (role) {
return [Number(role.id), role.name];
}));
const invitations = (data.invitations || []).map(function (invitation) {
return mapInvitationForView(invitation, roleNamesById);
});
res.send(pages.renderInvitationsPage({
invitations: invitations,
pagination: buildPagination(data.totalItems, data.currentPage, 'page', { search: search, sort: sort, direction: direction }, LIST_PAGE_SIZE, 'invitations', 'Invitation pages'),
message: req.query.message ? String(req.query.message) : ''
}, req.currentUser));
} catch (error) {
next(error);
}
});
app.post('/settings/invitations/:id/delete', requirePermission('invitations.delete'), async function (req, res, next) {
try {
const invitationId = Number(req.params.id);
if (!Number.isInteger(invitationId) || invitationId <= 0) {
return res.status(400).send('Invalid invitation.');
}
const [result] = await pool.query('DELETE FROM a_user_invitations WHERE id = ? AND used_at IS NULL', [invitationId]);
if (!result || !result.affectedRows) {
return res.status(404).send('Invitation not found.');
}
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.invitation_deleted', actorUserId: getAuditUserId(req), targetType: 'invitation', targetId: invitationId });
res.redirect('/settings/invitations?message=' + encodeURIComponent('Invitation deleted.'));
} catch (error) {
next(error);
}
});
app.post('/settings/invitations/:id/resend', requirePermission('invitations.allow'), async function (req, res, next) {
try {
const invitationId = Number(req.params.id);
if (!Number.isInteger(invitationId) || invitationId <= 0) {
return res.status(400).send('Invalid invitation.');
}
if (typeof sendAccountEmail !== 'function' || typeof createOneTimeToken !== 'function' || typeof hashSessionToken !== 'function') {
return res.status(503).send('Email delivery is not available.');
}
const settings = await fetchAppSettings(pool);
if (!settings['email.smtp_enabled']) {
return res.status(503).send('Email delivery is not configured.');
}
const [rows] = await pool.query('SELECT email, name, role_ids_json FROM a_user_invitations WHERE id = ? AND used_at IS NULL AND expires_at > NOW() LIMIT 1', [invitationId]);
if (!rows.length) {
return res.status(404).send('Invitation not found.');
}
const invitation = rows[0];
const token = createOneTimeToken();
const invitationUrl = getRequestOrigin(req) + '/accept-invite?token=' + encodeURIComponent(token);
const expiryHours = Number(settings['email.invitation_expiry_hours']);
await sendAccountEmail(settings, Object.assign({ to: invitation.email }, renderAccountEmailTemplate(settings['email.invitation_subject'], settings['email.invitation_body'], { url: invitationUrl, username: '', display_name: invitation.name || 'there', email: invitation.email, expiry_time: formatAccountEmailExpiry(expiryHours, 'hours'), action_alignment: settings['email.invitation_button_alignment'], action_label: settings['email.invitation_button_text'] })));
await pool.query('UPDATE a_user_invitations SET token_hash = ?, expires_at = DATE_ADD(NOW(), INTERVAL ' + expiryHours + ' HOUR), created_at = NOW(), created_by = ? WHERE id = ? AND used_at IS NULL', [hashSessionToken(token), getAuditUserId(req), invitationId]);
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.invitation_resent', actorUserId: getAuditUserId(req), targetType: 'invitation', targetId: invitationId, targetLabel: invitation.email });
res.redirect('/settings/invitations?message=' + encodeURIComponent('Invitation resent.'));
} catch (error) {
next(error);
}
});
app.get('/settings/users/new', requirePermission('users.create'), function (req, res) { app.get('/settings/users/new', requirePermission('users.create'), function (req, res) {
fetchRoleOptions().then(function (roles) { fetchRoleOptions().then(function (roles) {
res.send(pages.renderUsersAddPage(req.query.message ? String(req.query.message) : '', req.currentUser, mapRolesForForm(roles, []), {}, 'primary')); res.send(pages.renderUsersAddPage(req.query.message ? String(req.query.message) : '', req.currentUser, mapRolesForForm(roles, []), {}, 'primary'));
@@ -110,6 +205,54 @@
}); });
}); });
app.get('/settings/users/invite', requirePermission('invitations.create'), async function (req, res, next) {
try {
const roles = await fetchRoleOptions();
res.send(pages.renderUsersInvitePage('', req.currentUser, mapRolesForForm(roles, []), {}, 'success'));
} catch (error) {
next(error);
}
});
app.post('/settings/users/invite', requirePermission('invitations.create'), async function (req, res, next) {
try {
const email = common.validateMaxLength(req.body.email || '', USER_EMAIL_MAX_LENGTH, 'Email').toLowerCase();
const name = common.validateMaxLength(req.body.name || '', USER_NAME_MAX_LENGTH, 'Name');
const selectedRoleIds = readArrayField(req.body, ['role_ids[]', 'role_ids']);
const roleCheck = await validateRoleIds(selectedRoleIds);
const formValues = { email: email, name: name };
async function renderInviteError(message) {
const roles = await fetchRoleOptions();
return res.status(400).send(pages.renderUsersInvitePage(message, req.currentUser, mapRolesForForm(roles, selectedRoleIds), formValues, 'warning'));
}
if (!email || !EMAIL_PATTERN.test(email)) return renderInviteError('Email address is invalid.');
if (!name) return renderInviteError('Display name is required.');
if (!roleCheck.ok) return renderInviteError(roleCheck.message);
if (typeof sendAccountEmail !== 'function' || typeof createOneTimeToken !== 'function' || typeof hashSessionToken !== 'function') return renderInviteError('Email delivery is not available.');
const settings = await fetchAppSettings(pool);
if (!settings['email.smtp_enabled']) return renderInviteError('Email delivery is not configured.');
const [existingUsers] = await pool.query('SELECT id FROM a_users WHERE email = ? OR pending_email = ? LIMIT 1', [email, email]);
if (existingUsers.length) return renderInviteError('That email address is already associated with an account.');
const [recentInvites] = await pool.query('SELECT COUNT(*) AS invite_count FROM a_user_invitations WHERE created_by = ? AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)', [getAuditUserId(req)]);
if (Number(recentInvites[0] && recentInvites[0].invite_count) >= 25) return renderInviteError('Invitation sending is temporarily limited. Try again later.');
const token = createOneTimeToken();
await pool.query('UPDATE a_user_invitations SET used_at = NOW() WHERE email = ? AND used_at IS NULL', [email]);
const expiryHours = Number(settings['email.invitation_expiry_hours']);
await pool.query('INSERT INTO a_user_invitations (email, name, role_ids_json, token_hash, expires_at, created_by) VALUES (?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ' + expiryHours + ' HOUR), ?)', [email, name || null, JSON.stringify(roleCheck.roleIds), hashSessionToken(token), getAuditUserId(req)]);
const invitationUrl = getRequestOrigin(req) + '/accept-invite?token=' + encodeURIComponent(token);
try {
await sendAccountEmail(settings, Object.assign({ to: email }, renderAccountEmailTemplate(settings['email.invitation_subject'], settings['email.invitation_body'], { url: invitationUrl, username: '', display_name: name || 'there', email: email, expiry_time: formatAccountEmailExpiry(expiryHours, 'hours'), action_alignment: settings['email.invitation_button_alignment'], action_label: settings['email.invitation_button_text'] })));
} catch (mailError) {
await pool.query('DELETE FROM a_user_invitations WHERE token_hash = ?', [hashSessionToken(token)]);
throw mailError;
}
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.invitation_sent', actorUserId: getAuditUserId(req), targetType: 'email', targetLabel: email, details: { roleIds: roleCheck.roleIds } });
res.redirect('/settings/users?message=' + encodeURIComponent('Invitation sent.'));
} catch (error) {
next(error);
}
});
app.get('/settings/users/:id/duplicate', requirePermission('users.read'), requirePermission('users.create'), async function (req, res, next) { app.get('/settings/users/:id/duplicate', requirePermission('users.read'), requirePermission('users.create'), async function (req, res, next) {
try { try {
const userId = Number(req.params.id); const userId = Number(req.params.id);
@@ -166,7 +309,7 @@
return { return {
id: Number(session.id), id: Number(session.id),
ipAddress: String(session.ip_address || 'Unknown'), ipAddress: String(session.ip_address || 'Unknown'),
userAgent: String(session.user_agent || 'Unknown browser'), userAgent: formatUserAgentLabel(session.user_agent) || 'Unknown browser',
createdAtLabel: formatDashboardDate(session.created_at), createdAtLabel: formatDashboardDate(session.created_at),
lastUsedAtLabel: formatDashboardDate(session.last_used_at), lastUsedAtLabel: formatDashboardDate(session.last_used_at),
expiresAtLabel: formatDashboardDate(session.expires_at) expiresAtLabel: formatDashboardDate(session.expires_at)
@@ -222,6 +365,7 @@
try { try {
const name = common.validateMaxLength(req.body.name || '', USER_NAME_MAX_LENGTH, 'Name'); const name = common.validateMaxLength(req.body.name || '', USER_NAME_MAX_LENGTH, 'Name');
const username = common.validateMaxLength(req.body.username || '', USER_USERNAME_MAX_LENGTH, 'Username'); const username = common.validateMaxLength(req.body.username || '', USER_USERNAME_MAX_LENGTH, 'Username');
const email = common.validateMaxLength(req.body.email || '', USER_EMAIL_MAX_LENGTH, 'Email').toLowerCase();
const password = String(req.body.password || ''); const password = String(req.body.password || '');
const confirmPassword = String(req.body.confirm_password || ''); const confirmPassword = String(req.body.confirm_password || '');
const saveAction = String(req.body.save_action || req.body.action || '').trim().toLowerCase(); const saveAction = String(req.body.save_action || req.body.action || '').trim().toLowerCase();
@@ -229,7 +373,8 @@
const roleCheck = await validateRoleIds(selectedRoleIds); const roleCheck = await validateRoleIds(selectedRoleIds);
const formValues = { const formValues = {
username: username, username: username,
name: name name: name,
email: email
}; };
async function renderValidationError(message) { async function renderValidationError(message) {
@@ -243,6 +388,9 @@
if (!username) { if (!username) {
return renderValidationError('Username is required.'); return renderValidationError('Username is required.');
} }
if (email && !EMAIL_PATTERN.test(email)) {
return renderValidationError('Email address is invalid.');
}
const passwordStrengthMessage = validatePasswordStrength(password, await getPasswordRequirements()); const passwordStrengthMessage = validatePasswordStrength(password, await getPasswordRequirements());
if (passwordStrengthMessage) { if (passwordStrengthMessage) {
return renderValidationError(passwordStrengthMessage); return renderValidationError(passwordStrengthMessage);
@@ -267,8 +415,8 @@
const actorId = getAuditUserId(req); const actorId = getAuditUserId(req);
await connection.beginTransaction(); await connection.beginTransaction();
const [result] = await connection.query( const [result] = await connection.query(
'INSERT INTO a_users (name, username, password_hash, password_salt, password_iterations, must_change_password, created_by, modified_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', 'INSERT INTO a_users (name, username, email, password_hash, password_salt, password_iterations, must_change_password, created_by, modified_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
[name, username, passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations, mustChangePassword ? 1 : 0, actorId, actorId] [name, username, email || null, passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations, mustChangePassword ? 1 : 0, actorId, actorId]
); );
await rbacData.syncUserRoles(connection, result.insertId, roleCheck.roleIds); await rbacData.syncUserRoles(connection, result.insertId, roleCheck.roleIds);
await connection.commit(); await connection.commit();
@@ -364,7 +512,9 @@
} }
const username = common.validateMaxLength(req.body.username || user.username || '', USER_USERNAME_MAX_LENGTH, 'Username'); const username = common.validateMaxLength(req.body.username || user.username || '', USER_USERNAME_MAX_LENGTH, 'Username');
const email = common.validateMaxLength(req.body.email || '', USER_EMAIL_MAX_LENGTH, 'Email').toLowerCase();
const accountLocked = req.body.account_locked === '1' || (Array.isArray(req.body.account_locked) && req.body.account_locked.includes('1')); const accountLocked = req.body.account_locked === '1' || (Array.isArray(req.body.account_locked) && req.body.account_locked.includes('1'));
const emailVerified = req.body.email_verified === '1' || (Array.isArray(req.body.email_verified) && req.body.email_verified.includes('1'));
const [countRows] = await pool.query('SELECT COUNT(*) AS user_count FROM a_users'); const [countRows] = await pool.query('SELECT COUNT(*) AS user_count FROM a_users');
const canDelete = !countRows.length || Number(countRows[0].user_count) > 1; const canDelete = !countRows.length || Number(countRows[0].user_count) > 1;
@@ -386,6 +536,9 @@
if (!username) { if (!username) {
return renderValidationError('Username is required.'); return renderValidationError('Username is required.');
} }
if (email && !EMAIL_PATTERN.test(email)) {
return renderValidationError('Email address is invalid.');
}
if (shouldUpdatePassword) { if (shouldUpdatePassword) {
const passwordStrengthMessage = validatePasswordStrength(password, await getPasswordRequirements()); const passwordStrengthMessage = validatePasswordStrength(password, await getPasswordRequirements());
if (passwordStrengthMessage) { if (passwordStrengthMessage) {
@@ -410,12 +563,14 @@
const changes = buildAuditChanges({ const changes = buildAuditChanges({
name: user.name, name: user.name,
username: user.username, username: user.username,
email: user.email || '',
roleIds: user.roleIds, roleIds: user.roleIds,
accountLocked: Boolean(user.account_locked), accountLocked: Boolean(user.account_locked),
passwordReset: false passwordReset: false
}, { }, {
name: name, name: name,
username: username, username: username,
email: email,
roleIds: roleCheck.roleIds, roleIds: roleCheck.roleIds,
accountLocked: accountLocked, accountLocked: accountLocked,
passwordReset: shouldUpdatePassword passwordReset: shouldUpdatePassword
@@ -426,6 +581,10 @@
await connection.rollback(); await connection.rollback();
return res.status(404).send('User not found.'); return res.status(404).send('User not found.');
} }
await connection.query('UPDATE a_users SET email = ?, email_verified_at = CASE WHEN email = ? THEN email_verified_at ELSE NULL END, modified_by = ? WHERE id = ?', [email || null, email || null, getAuditUserId(req), userId]);
if (emailVerified && email && (await fetchAppSettings(pool))['security.allow_admin_email_verification_bypass']) {
await connection.query('UPDATE a_users SET email_verified_at = NOW() WHERE id = ? AND email = ?', [userId, email]);
}
await rbacData.syncUserRoles(connection, userId, roleCheck.roleIds); await rbacData.syncUserRoles(connection, userId, roleCheck.roleIds);
if (accountLocked) { if (accountLocked) {
await connection.query('DELETE FROM a_sessions WHERE user_id = ?', [userId]); await connection.query('DELETE FROM a_sessions WHERE user_id = ?', [userId]);
@@ -471,6 +630,17 @@
details: { source: 'administrator' } details: { source: 'administrator' }
}); });
} }
if (emailVerified && !user.email_verified_at && email) {
await recordRequestAuditEvent(pool, req, {
category: 'security',
eventType: 'email.verification_bypassed',
actorUserId: req.currentUser.id,
targetType: 'user',
targetId: userId,
targetLabel: username,
details: { source: 'administrator' }
});
}
} }
if (saveAction === 'new') { if (saveAction === 'new') {
return res.redirect('/settings/users/new?message=' + encodeURIComponent('User updated.')); return res.redirect('/settings/users/new?message=' + encodeURIComponent('User updated.'));
+27
View File
@@ -0,0 +1,27 @@
const { renderView } = require('../../view');
module.exports = function renderAcceptInvitePage(message, token, email, name, passwordRequirements, isValidInvitation) {
const requirements = passwordRequirements || { minimumLength: 10, minimumCategories: 3, requireLowercase: false, requireUppercase: false, requireNumber: false, requireSymbol: false };
const requiredCategories = [];
if (requirements.requireLowercase) requiredCategories.push('lowercase');
if (requirements.requireUppercase) requiredCategories.push('uppercase');
if (requirements.requireNumber) requiredCategories.push('number');
if (requirements.requireSymbol) requiredCategories.push('symbol');
const passwordRequirementsText = requiredCategories.length
? 'Use at least ' + requirements.minimumLength + ' characters and include ' + requiredCategories.join(', ') + '.'
: requirements.minimumCategories === 4
? 'Use at least ' + requirements.minimumLength + ' characters and include uppercase, lowercase, number, and symbol.'
: 'Use at least ' + requirements.minimumLength + ' characters and include ' + requirements.minimumCategories + ' of: uppercase, lowercase, number, and symbol.';
return renderView('auth/accept-invite', {
title: 'Accept invitation',
authShell: true,
bodyClass: 'login-page-body',
message: message || '',
isValidInvitation: Boolean(isValidInvitation),
token: token || '',
email: email || '',
name: name || '',
passwordMinimumLength: requirements.minimumLength,
passwordRequirementsText: passwordRequirementsText
});
};
@@ -0,0 +1,5 @@
const { renderView } = require('../../view');
module.exports = function renderEmailVerificationErrorPage(message) {
return renderView('auth/email-verification-error', { title: 'Verification link unavailable', authShell: true, bodyClass: 'login-page-body', message: message || 'This email verification link is invalid or has expired.' });
};
+5
View File
@@ -0,0 +1,5 @@
const { renderView } = require('../../view');
module.exports = function renderEmailVerifiedPage() {
return renderView('auth/email-verified', { title: 'Email verified', authShell: true, bodyClass: 'login-page-body' });
};
+5
View File
@@ -0,0 +1,5 @@
const { renderView } = require('../../view');
module.exports = function renderForgotPasswordPage(message) {
return renderView('auth/forgot-password', { title: 'Reset password', authShell: true, bodyClass: 'login-page-body', message: message || '' });
};
+152 -3
View File
@@ -2,6 +2,7 @@
const { normalizeReturnToPath, getRequestOrigin } = require('../../lib/auth/session'); const { normalizeReturnToPath, getRequestOrigin } = require('../../lib/auth/session');
const { fetchAppSettings } = require('#src/data/app-settings'); const { fetchAppSettings } = require('#src/data/app-settings');
const { formatAccountEmailExpiry, renderAccountEmailTemplate } = require('#src/data/account-email-templates');
module.exports = function registerAuthRoutes(app, deps) { module.exports = function registerAuthRoutes(app, deps) {
const pool = deps.pool; const pool = deps.pool;
@@ -17,6 +18,10 @@ module.exports = function registerAuthRoutes(app, deps) {
const verifyPassword = deps.verifyPassword; const verifyPassword = deps.verifyPassword;
const sessionCookieName = deps.sessionCookieName; const sessionCookieName = deps.sessionCookieName;
const recordRequestAuditEvent = deps.recordRequestAuditEvent; const recordRequestAuditEvent = deps.recordRequestAuditEvent;
const sendAccountEmail = deps.sendAccountEmail;
const createOneTimeToken = deps.createOneTimeToken;
const getConnection = deps.getConnection;
const rbacData = deps.rbacData;
function getReturnTo(req) { function getReturnTo(req) {
return normalizeReturnToPath(req && (req.query && req.query.returnTo || req.body && req.body.returnTo), getRequestOrigin(req)); return normalizeReturnToPath(req && (req.query && req.query.returnTo || req.body && req.body.returnTo), getRequestOrigin(req));
@@ -77,6 +82,142 @@ module.exports = function registerAuthRoutes(app, deps) {
await pool.query('DELETE FROM a_login_attempts WHERE rate_key = ?', [rateKey]); await pool.query('DELETE FROM a_login_attempts WHERE rate_key = ?', [rateKey]);
} }
async function getPasswordRequirements() {
const settings = await fetchAppSettings(pool);
return {
minimumLength: settings['security.password_min_length'],
minimumCategories: settings['security.password_min_categories'],
requireLowercase: settings['security.password_require_lowercase'],
requireUppercase: settings['security.password_require_uppercase'],
requireNumber: settings['security.password_require_number'],
requireSymbol: settings['security.password_require_symbol']
};
}
app.get('/accept-invite', async function (req, res, next) {
try {
const token = String(req.query.token || '').trim();
const [rows] = await pool.query('SELECT email, name FROM a_user_invitations WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW() LIMIT 1', [hashSessionToken(token)]);
const invitation = rows[0] || null;
if (!invitation) return res.status(400).send(pages.renderAcceptInvitePage('This invitation is invalid or has expired.', token, '', '', await getPasswordRequirements(), false));
res.send(pages.renderAcceptInvitePage('', token, invitation.email, invitation.name, await getPasswordRequirements(), true));
} catch (error) {
next(error);
}
});
app.post('/accept-invite', async function (req, res, next) {
const connection = typeof getConnection === 'function' ? await getConnection() : pool;
try {
const token = String(req.body.token || '').trim();
const username = String(req.body.username || '').trim();
const name = String(req.body.name || '').trim();
const password = String(req.body.password || '');
const confirmPassword = String(req.body.confirm_password || '');
const [rows] = await connection.query('SELECT id, email, name, role_ids_json FROM a_user_invitations WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW() LIMIT 1', [hashSessionToken(token)]);
const invitation = rows[0] || null;
const requirements = await getPasswordRequirements();
const renderError = function (message) { return res.status(400).send(pages.renderAcceptInvitePage(message, token, invitation ? invitation.email : '', name || (invitation && invitation.name) || '', requirements, Boolean(invitation))); };
if (!invitation) return renderError('This invitation is invalid or has expired.');
if (!username) return renderError('Username is required.');
if (!name) return renderError('Name is required.');
const [existingUsers] = await connection.query('SELECT id FROM a_users WHERE username = ? LIMIT 1', [username]);
if (existingUsers.length) return renderError('That username already exists.');
const strengthMessage = deps.validatePasswordStrength(password, requirements);
if (strengthMessage) return renderError(strengthMessage);
if (password !== confirmPassword) return renderError('Passwords do not match.');
const passwordRecord = deps.hashPassword(password);
const roleIds = JSON.parse(invitation.role_ids_json || '[]');
await connection.beginTransaction();
const [result] = await connection.query('INSERT INTO a_users (name, username, email, email_verified_at, password_hash, password_salt, password_iterations, created_by, modified_by) VALUES (?, ?, ?, NOW(), ?, ?, ?, NULL, NULL)', [name, username, invitation.email, passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations]);
if (rbacData && typeof rbacData.syncUserRoles === 'function') await rbacData.syncUserRoles(connection, result.insertId, roleIds);
await connection.query('UPDATE a_user_invitations SET used_at = NOW() WHERE id = ? AND used_at IS NULL', [invitation.id]);
await connection.commit();
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'users', eventType: 'user.invitation_accepted', targetType: 'user', targetId: result.insertId, targetLabel: username, details: { invitationId: invitation.id } });
res.redirect('/login?message=' + encodeURIComponent('Account created. You can now sign in.'));
} catch (error) {
try { await connection.rollback(); } catch (_rollbackError) {}
next(error);
} finally {
if (connection !== pool && connection && typeof connection.release === 'function') connection.release();
}
});
app.get('/forgot-password', function (req, res) {
res.send(pages.renderForgotPasswordPage(''));
});
app.post('/forgot-password', async function (req, res, next) {
try {
const identity = String(req.body.identity || '').trim();
const genericMessage = 'If that account has a verified email address, a reset link has been sent.';
const [rows] = await pool.query('SELECT id, name, username, email FROM a_users WHERE username = ? OR (email = ? AND email_verified_at IS NOT NULL) LIMIT 1', [identity, identity.toLowerCase()]);
const user = rows[0] || null;
const settings = await fetchAppSettings(pool);
if (user && user.email && user.email_verified_at && typeof sendAccountEmail === 'function' && typeof createOneTimeToken === 'function') {
const token = createOneTimeToken();
await pool.query('DELETE FROM a_account_tokens WHERE user_id = ? AND token_type = ?', [user.id, 'password-reset']);
const expiryMinutes = Number(settings['email.reset_expiry_minutes']);
await pool.query('INSERT INTO a_account_tokens (user_id, token_type, token_hash, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL ' + expiryMinutes + ' MINUTE))', [user.id, 'password-reset', hashSessionToken(token)]);
const resetUrl = getRequestOrigin(req) + '/reset-password?token=' + encodeURIComponent(token);
try {
await sendAccountEmail(settings, Object.assign({ to: user.email }, renderAccountEmailTemplate(settings['email.reset_subject'], settings['email.reset_body'], { url: resetUrl, username: user.username, display_name: user.name, email: user.email, expiry_time: formatAccountEmailExpiry(expiryMinutes, 'minutes'), action_alignment: settings['email.reset_button_alignment'], action_label: settings['email.reset_button_text'] })));
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'security', eventType: 'password.reset_requested', targetType: 'user', targetId: user.id, targetLabel: user.username });
} catch (_mailError) {
await pool.query('DELETE FROM a_account_tokens WHERE token_hash = ?', [hashSessionToken(token)]);
}
}
res.send(pages.renderForgotPasswordPage(genericMessage));
} catch (error) {
next(error);
}
});
app.get('/reset-password', async function (req, res, next) {
try {
const token = String(req.query.token || '').trim();
if (!token) return res.redirect('/forgot-password');
res.send(pages.renderResetPasswordPage('', token, await getPasswordRequirements()));
} catch (error) {
next(error);
}
});
app.post('/reset-password', async function (req, res, next) {
try {
const token = String(req.body.token || '');
const password = String(req.body.password || '');
const confirmPassword = String(req.body.confirm_password || '');
const [rows] = await pool.query('SELECT t.id AS token_id, t.user_id, u.username, u.email FROM a_account_tokens t JOIN a_users u ON u.id = t.user_id WHERE t.token_hash = ? AND t.token_type = ? AND t.used_at IS NULL AND t.expires_at > NOW() LIMIT 1', [hashSessionToken(token), 'password-reset']);
const record = rows[0] || null;
if (!record) return res.status(400).send(pages.renderResetPasswordPage('This reset link is invalid or has expired.', token, await getPasswordRequirements()));
const strengthMessage = deps.validatePasswordStrength(password, await getPasswordRequirements());
if (strengthMessage || password !== confirmPassword) return res.status(400).send(pages.renderResetPasswordPage(strengthMessage || 'Passwords do not match.', token, await getPasswordRequirements()));
const passwordRecord = deps.hashPassword(password);
await pool.query('UPDATE a_users SET password_hash = ?, password_salt = ?, password_iterations = ?, must_change_password = 0, modified_at = CURRENT_TIMESTAMP WHERE id = ?', [passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations, record.user_id]);
await pool.query('UPDATE a_account_tokens SET used_at = NOW() WHERE id = ?', [record.token_id]);
await pool.query('DELETE FROM a_sessions WHERE user_id = ?', [record.user_id]);
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'security', eventType: 'password.reset', targetType: 'user', targetId: record.user_id, targetLabel: record.username, details: { source: 'email' } });
res.redirect('/login?message=' + encodeURIComponent('Password updated. You can now sign in.'));
} catch (error) {
next(error);
}
});
app.get('/verify-email', async function (req, res, next) {
try {
const tokenHash = hashSessionToken(String(req.query.token || ''));
const [rows] = await pool.query('SELECT id FROM a_users WHERE pending_email_token_hash = ? AND pending_email_expires_at > NOW() LIMIT 1', [tokenHash]);
const user = rows[0] || null;
if (!user) return res.status(400).send(pages.renderEmailVerificationErrorPage('This email verification link is invalid or has expired.'));
await pool.query('UPDATE a_users SET email = pending_email, email_verified_at = NOW(), pending_email = NULL, pending_email_token_hash = NULL, pending_email_expires_at = NULL WHERE id = ?', [user.id]);
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'security', eventType: 'email.verification_completed', targetType: 'user', targetId: user.id });
res.send(pages.renderEmailVerifiedPage());
} catch (error) {
next(error);
}
});
app.get('/', function (req, res) { app.get('/', function (req, res) {
res.redirect(req.currentUser ? '/dashboard' : '/login'); res.redirect(req.currentUser ? '/dashboard' : '/login');
}); });
@@ -90,7 +231,11 @@ module.exports = function registerAuthRoutes(app, deps) {
const message = typeof consumeAuthMessageCookie === 'function' const message = typeof consumeAuthMessageCookie === 'function'
? consumeAuthMessageCookie(req, res) ? consumeAuthMessageCookie(req, res)
: (req.query.message ? String(req.query.message) : ''); : (req.query.message ? String(req.query.message) : '');
res.send(pages.renderLoginPage(message, returnTo, req.query.username ? String(req.query.username) : '')); fetchAppSettings(pool).then(function (settings) {
res.send(pages.renderLoginPage(message, returnTo, req.query.username ? String(req.query.username) : '', Boolean(settings['email.smtp_enabled'])));
}).catch(function (error) {
res.status(500).send(error.message || 'Unable to load login settings.');
});
}); });
app.post('/login', async function (req, res, next) { app.post('/login', async function (req, res, next) {
@@ -123,8 +268,12 @@ module.exports = function registerAuthRoutes(app, deps) {
return res.status(401).send(pages.renderLoginPage(message, returnTo, username)); return res.status(401).send(pages.renderLoginPage(message, returnTo, username));
} }
const [rows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations, account_locked FROM a_users WHERE username = ? LIMIT 1', [username]); const [usernameRows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations, account_locked FROM a_users WHERE username = ? LIMIT 1', [username]);
const user = rows[0] || null; let user = usernameRows[0] || null;
if (!user) {
const [emailRows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations, account_locked FROM a_users WHERE email = ? AND email_verified_at IS NOT NULL LIMIT 1', [username.toLowerCase()]);
user = emailRows[0] || null;
}
if (user && user.account_locked) { if (user && user.account_locked) {
if (typeof recordRequestAuditEvent === 'function') { if (typeof recordRequestAuditEvent === 'function') {
await recordRequestAuditEvent(pool, req, { await recordRequestAuditEvent(pool, req, {
+2 -1
View File
@@ -2,7 +2,7 @@
const { renderView } = require('../../view'); const { renderView } = require('../../view');
module.exports = function renderLoginPage(message, returnTo, username) { module.exports = function renderLoginPage(message, returnTo, username, showForgotPassword) {
return renderView('auth/login', { return renderView('auth/login', {
title: 'Sign in', title: 'Sign in',
authShell: true, authShell: true,
@@ -10,6 +10,7 @@ module.exports = function renderLoginPage(message, returnTo, username) {
message: message || '', message: message || '',
returnTo: returnTo || '', returnTo: returnTo || '',
username: username || '', username: username || '',
showForgotPassword: Boolean(showForgotPassword),
messageVariant: 'warning' messageVariant: 'warning'
}); });
}; };
+16
View File
@@ -0,0 +1,16 @@
const { renderView } = require('../../view');
module.exports = function renderResetPasswordPage(message, token, passwordRequirements) {
const requirements = passwordRequirements || { minimumLength: 10, minimumCategories: 3, requireLowercase: false, requireUppercase: false, requireNumber: false, requireSymbol: false };
const requiredCategories = [];
if (requirements.requireLowercase) requiredCategories.push('lowercase');
if (requirements.requireUppercase) requiredCategories.push('uppercase');
if (requirements.requireNumber) requiredCategories.push('number');
if (requirements.requireSymbol) requiredCategories.push('symbol');
const passwordRequirementsText = requiredCategories.length
? 'Use at least ' + requirements.minimumLength + ' characters and include ' + requiredCategories.join(', ') + '.'
: requirements.minimumCategories === 4
? 'Use at least ' + requirements.minimumLength + ' characters and include uppercase, lowercase, number, and symbol.'
: 'Use at least ' + requirements.minimumLength + ' characters and include ' + requirements.minimumCategories + ' of: uppercase, lowercase, number, and symbol.';
return renderView('auth/reset-password', { title: 'Choose a new password', authShell: true, bodyClass: 'login-page-body', message: message || '', token: token || '', passwordMinimumLength: requirements.minimumLength, passwordRequirementsText: passwordRequirementsText });
};
@@ -26,6 +26,9 @@ function buildDuplicateApiSource(apiSource, duplicateName) {
tokenUrl: apiSource.token_url || '', tokenUrl: apiSource.token_url || '',
tokenRequestBodyJson: apiSource.token_request_body_json || '', tokenRequestBodyJson: apiSource.token_request_body_json || '',
tokenResponsePath: apiSource.token_response_path || 'access_token', tokenResponsePath: apiSource.token_response_path || 'access_token',
tokenRefreshUrl: apiSource.token_refresh_url || '',
tokenRefreshRequestBodyJson: apiSource.token_refresh_request_body_json || '',
tokenRefreshResponsePath: apiSource.token_refresh_response_path || 'refresh_token',
tokenHeaderName: apiSource.token_header_name || 'Authorization', tokenHeaderName: apiSource.token_header_name || 'Authorization',
tokenHeaderPrefix: apiSource.token_header_prefix || 'Bearer', tokenHeaderPrefix: apiSource.token_header_prefix || 'Bearer',
itemsPath: apiSource.items_path || '' itemsPath: apiSource.items_path || ''
@@ -21,6 +21,9 @@ module.exports = function renderApiSourceEditPage(apiSource, data, message, curr
tokenUrl: apiSource.token_url || '', tokenUrl: apiSource.token_url || '',
tokenRequestBodyJson: apiSource.token_request_body_json || '', tokenRequestBodyJson: apiSource.token_request_body_json || '',
tokenResponsePath: apiSource.token_response_path || 'access_token', tokenResponsePath: apiSource.token_response_path || 'access_token',
tokenRefreshUrl: apiSource.token_refresh_url || '',
tokenRefreshRequestBodyJson: apiSource.token_refresh_request_body_json || '',
tokenRefreshResponsePath: apiSource.token_refresh_response_path || 'refresh_token',
tokenHeaderName: apiSource.token_header_name || 'Authorization', tokenHeaderName: apiSource.token_header_name || 'Authorization',
tokenHeaderPrefix: apiSource.token_header_prefix || 'Bearer', tokenHeaderPrefix: apiSource.token_header_prefix || 'Bearer',
itemsPath: apiSource.items_path || '', itemsPath: apiSource.items_path || '',
@@ -17,6 +17,9 @@ function buildDefaultApiSource() {
tokenUrl: '', tokenUrl: '',
tokenRequestBodyJson: '', tokenRequestBodyJson: '',
tokenResponsePath: 'access_token', tokenResponsePath: 'access_token',
tokenRefreshUrl: '',
tokenRefreshRequestBodyJson: '',
tokenRefreshResponsePath: 'refresh_token',
tokenHeaderName: 'Authorization', tokenHeaderName: 'Authorization',
tokenHeaderPrefix: 'Bearer', tokenHeaderPrefix: 'Bearer',
itemsPath: '', itemsPath: '',
@@ -105,6 +105,9 @@ module.exports = function registerApiSourceRoutes(app, deps) {
authHeaderValue: apiSource.auth_header_value || '', authHeaderValue: apiSource.auth_header_value || '',
tokenUrl: apiSource.token_url || '', tokenUrl: apiSource.token_url || '',
tokenResponsePath: apiSource.token_response_path || 'access_token', tokenResponsePath: apiSource.token_response_path || 'access_token',
tokenRefreshUrl: apiSource.token_refresh_url || '',
tokenRefreshRequestBodyJson: apiSource.token_refresh_request_body_json || '',
tokenRefreshResponsePath: apiSource.token_refresh_response_path || 'refresh_token',
itemsPath: apiSource.items_path || '', itemsPath: apiSource.items_path || '',
intervalLabel: apiSource.update_interval_unit === 'seconds' intervalLabel: apiSource.update_interval_unit === 'seconds'
? (Math.max(1, Number(apiSource.update_interval_value) || 0) === 1 ? 'Every second' : `Every ${Math.max(1, Number(apiSource.update_interval_value) || 0)} seconds`) ? (Math.max(1, Number(apiSource.update_interval_value) || 0) === 1 ? 'Every second' : `Every ${Math.max(1, Number(apiSource.update_interval_value) || 0)} seconds`)
@@ -183,6 +186,9 @@ module.exports = function registerApiSourceRoutes(app, deps) {
tokenUrl: apiSource.token_url || '', tokenUrl: apiSource.token_url || '',
tokenRequestBodyJson: apiSource.token_request_body_json || '', tokenRequestBodyJson: apiSource.token_request_body_json || '',
tokenResponsePath: apiSource.token_response_path || 'access_token', tokenResponsePath: apiSource.token_response_path || 'access_token',
tokenRefreshUrl: apiSource.token_refresh_url || '',
tokenRefreshRequestBodyJson: apiSource.token_refresh_request_body_json || '',
tokenRefreshResponsePath: apiSource.token_refresh_response_path || 'refresh_token',
tokenHeaderName: apiSource.token_header_name || 'Authorization', tokenHeaderName: apiSource.token_header_name || 'Authorization',
tokenHeaderPrefix: apiSource.token_header_prefix || 'Bearer', tokenHeaderPrefix: apiSource.token_header_prefix || 'Bearer',
itemsPath: apiSource.items_path || '', itemsPath: apiSource.items_path || '',
@@ -242,8 +248,8 @@ module.exports = function registerApiSourceRoutes(app, deps) {
const actorId = getAuditUserId(req); const actorId = getAuditUserId(req);
await connection.beginTransaction(); await connection.beginTransaction();
const [result] = await connection.query( const [result] = await connection.query(
'INSERT INTO i_api_sources (name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_header_name, token_header_prefix, items_path, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_by, modified_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', 'INSERT INTO i_api_sources (name, api_url, request_method, request_body_json, auth_method, auth_username, auth_password, auth_bearer_token, auth_header_name, auth_header_value, token_url, token_request_body_json, token_response_path, token_refresh_url, token_refresh_request_body_json, token_refresh_response_path, token_header_name, token_header_prefix, items_path, update_interval_value, update_interval_unit, last_pulled_at, last_pull_error, last_response_status, last_response_content_type, last_response_json, created_by, modified_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[payload.name, payload.apiUrl, payload.requestMethod, payload.requestBodyJson || null, payload.authMethod, payload.authUsername || null, payload.authPassword || null, payload.authBearerToken || null, payload.authHeaderName || null, payload.authHeaderValue || null, payload.tokenUrl || null, payload.tokenRequestBodyJson || null, payload.tokenResponsePath || null, payload.tokenHeaderName || null, payload.tokenHeaderPrefix || null, payload.itemsPath || null, payload.updateIntervalValue, payload.updateIntervalUnit, null, null, null, null, null, actorId, actorId] [payload.name, payload.apiUrl, payload.requestMethod, payload.requestBodyJson || null, payload.authMethod, payload.authUsername || null, payload.authPassword || null, payload.authBearerToken || null, payload.authHeaderName || null, payload.authHeaderValue || null, payload.tokenUrl || null, payload.tokenRequestBodyJson || null, payload.tokenResponsePath || null, payload.tokenRefreshUrl || null, payload.tokenRefreshRequestBodyJson || null, payload.tokenRefreshResponsePath || null, payload.tokenHeaderName || null, payload.tokenHeaderPrefix || null, payload.itemsPath || null, payload.updateIntervalValue, payload.updateIntervalUnit, null, null, null, null, null, actorId, actorId]
); );
await connection.commit(); await connection.commit();
dataSourceTasks.registerRecurringRefresh('api-source', result.insertId, payload.name, payload.updateIntervalValue, payload.updateIntervalUnit, function () { dataSourceTasks.registerRecurringRefresh('api-source', result.insertId, payload.name, payload.updateIntervalValue, payload.updateIntervalUnit, function () {
@@ -308,8 +314,8 @@ module.exports = function registerApiSourceRoutes(app, deps) {
const actorId = getAuditUserId(req); const actorId = getAuditUserId(req);
await connection.beginTransaction(); await connection.beginTransaction();
await connection.query( await connection.query(
'UPDATE i_api_sources SET name = ?, api_url = ?, request_method = ?, request_body_json = ?, auth_method = ?, auth_username = ?, auth_password = ?, auth_bearer_token = ?, auth_header_name = ?, auth_header_value = ?, token_url = ?, token_request_body_json = ?, token_response_path = ?, token_header_name = ?, token_header_prefix = ?, items_path = ?, update_interval_value = ?, update_interval_unit = ?, modified_by = ? WHERE id = ?', 'UPDATE i_api_sources SET name = ?, api_url = ?, request_method = ?, request_body_json = ?, auth_method = ?, auth_username = ?, auth_password = ?, auth_bearer_token = ?, auth_header_name = ?, auth_header_value = ?, token_url = ?, token_request_body_json = ?, token_response_path = ?, token_refresh_url = ?, token_refresh_request_body_json = ?, token_refresh_response_path = ?, token_header_name = ?, token_header_prefix = ?, items_path = ?, update_interval_value = ?, update_interval_unit = ?, modified_by = ? WHERE id = ?',
[payload.name, payload.apiUrl, payload.requestMethod, payload.requestBodyJson || null, payload.authMethod, payload.authUsername || null, payload.authPassword || null, payload.authBearerToken || null, payload.authHeaderName || null, payload.authHeaderValue || null, payload.tokenUrl || null, payload.tokenRequestBodyJson || null, payload.tokenResponsePath || null, payload.tokenHeaderName || null, payload.tokenHeaderPrefix || null, payload.itemsPath || null, payload.updateIntervalValue, payload.updateIntervalUnit, actorId, apiSource.id] [payload.name, payload.apiUrl, payload.requestMethod, payload.requestBodyJson || null, payload.authMethod, payload.authUsername || null, payload.authPassword || null, payload.authBearerToken || null, payload.authHeaderName || null, payload.authHeaderValue || null, payload.tokenUrl || null, payload.tokenRequestBodyJson || null, payload.tokenResponsePath || null, payload.tokenRefreshUrl || null, payload.tokenRefreshRequestBodyJson || null, payload.tokenRefreshResponsePath || null, payload.tokenHeaderName || null, payload.tokenHeaderPrefix || null, payload.itemsPath || null, payload.updateIntervalValue, payload.updateIntervalUnit, actorId, apiSource.id]
); );
await connection.commit(); await connection.commit();
if (apiSource.enabled === 0 || apiSource.enabled === false) { if (apiSource.enabled === 0 || apiSource.enabled === false) {
+7
View File
@@ -6,6 +6,7 @@ const renderWeatherLocationAddPage = require('./weather/add');
const renderWeatherLocationEditPage = require('./weather/edit'); const renderWeatherLocationEditPage = require('./weather/edit');
const { buildDuplicateWeatherLocationName, buildDuplicateWeatherLocation } = require('./weather/duplicate'); const { buildDuplicateWeatherLocationName, buildDuplicateWeatherLocation } = require('./weather/duplicate');
const { fetchAppSettings } = require('../../../data/app-settings'); const { fetchAppSettings } = require('../../../data/app-settings');
const { buildAuditChanges } = require('../../../data/audit-log');
async function getWeatherLocationUsageIds(pool, common) { async function getWeatherLocationUsageIds(pool, common) {
const [slides] = await pool.query('SELECT content_json FROM c_slides WHERE content_json IS NOT NULL'); const [slides] = await pool.query('SELECT content_json FROM c_slides WHERE content_json IS NOT NULL');
@@ -42,6 +43,7 @@ module.exports = function registerWeatherRoutes(app, deps) {
const dataSourceTasks = deps.dataSourceTasks; const dataSourceTasks = deps.dataSourceTasks;
const backgroundTaskQueue = deps.backgroundTaskQueue; const backgroundTaskQueue = deps.backgroundTaskQueue;
const requirePermission = deps.requirePermission; const requirePermission = deps.requirePermission;
const recordRequestAuditEvent = deps.recordRequestAuditEvent;
const listPageSize = 25; const listPageSize = 25;
async function getProviderAvailability() { async function getProviderAvailability() {
const settings = await fetchAppSettings(pool); const settings = await fetchAppSettings(pool);
@@ -121,6 +123,7 @@ module.exports = function registerWeatherRoutes(app, deps) {
return dataSourceTasks.refreshWeatherLocationInBackground(result.insertId, null); return dataSourceTasks.refreshWeatherLocationInBackground(result.insertId, null);
}); });
await backgroundTaskQueue.enqueueTask({ key: 'weather-location-refresh:' + result.insertId, title: 'Weather location refresh', category: 'data-source', taskType: 'data-source-refresh', payload: { sourceType: 'weather-location', sourceId: result.insertId, sourceName: payload.name, actorId: actorId }, metadata: { sourceType: 'weather-location', sourceId: result.insertId, sourceName: payload.name } }); await backgroundTaskQueue.enqueueTask({ key: 'weather-location-refresh:' + result.insertId, title: 'Weather location refresh', category: 'data-source', taskType: 'data-source-refresh', payload: { sourceType: 'weather-location', sourceId: result.insertId, sourceName: payload.name, actorId: actorId }, metadata: { sourceType: 'weather-location', sourceId: result.insertId, sourceName: payload.name } });
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'weather', eventType: 'weather-location.created', actorUserId: actorId, targetType: 'weather-location', targetId: result.insertId, targetLabel: payload.name });
redirectAfterSave(req, res, '/data-sources/weather/' + result.insertId + '/edit', { closeUrl: '/data-sources/weather', newUrl: '/data-sources/weather/new', message: 'Weather location created.' }); redirectAfterSave(req, res, '/data-sources/weather/' + result.insertId + '/edit', { closeUrl: '/data-sources/weather', newUrl: '/data-sources/weather/new', message: 'Weather location created.' });
} catch (error) { } catch (error) {
try { await connection.rollback(); } catch (_rollbackError) { } try { await connection.rollback(); } catch (_rollbackError) { }
@@ -143,6 +146,7 @@ module.exports = function registerWeatherRoutes(app, deps) {
} else { } else {
dataSourceTasks.removeRecurringRefresh('weather-location', location.id); dataSourceTasks.removeRecurringRefresh('weather-location', location.id);
} }
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'weather', eventType: enabled ? 'weather-location.enabled' : 'weather-location.disabled', actorUserId: getAuditUserId(req), targetType: 'weather-location', targetId: location.id, targetLabel: location.name });
return res.redirect('/data-sources/weather/' + location.id + '/edit?message=' + encodeURIComponent(enabled ? 'Weather location enabled.' : 'Weather location disabled.')); return res.redirect('/data-sources/weather/' + location.id + '/edit?message=' + encodeURIComponent(enabled ? 'Weather location enabled.' : 'Weather location disabled.'));
} }
const payload = common.buildWeatherLocationPayload(req, location); const payload = common.buildWeatherLocationPayload(req, location);
@@ -159,6 +163,7 @@ module.exports = function registerWeatherRoutes(app, deps) {
return dataSourceTasks.refreshWeatherLocationInBackground(location.id, null); return dataSourceTasks.refreshWeatherLocationInBackground(location.id, null);
}); });
} }
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'weather', eventType: 'weather-location.updated', actorUserId: getAuditUserId(req), targetType: 'weather-location', targetId: location.id, targetLabel: payload.name, details: { changes: buildAuditChanges({ name: location.name, locationLabel: location.location_label, latitude: location.latitude, longitude: location.longitude, timezone: location.timezone, provider: location.provider, temperatureUnit: location.temperature_unit, windUnit: location.wind_unit, precipitationUnit: location.precipitation_unit, updateIntervalValue: location.update_interval_value, updateIntervalUnit: location.update_interval_unit }, payload) } });
redirectAfterSave(req, res, '/data-sources/weather/' + location.id + '/edit', { closeUrl: '/data-sources/weather', newUrl: '/data-sources/weather/new', message: 'Weather location updated.' }); redirectAfterSave(req, res, '/data-sources/weather/' + location.id + '/edit', { closeUrl: '/data-sources/weather', newUrl: '/data-sources/weather/new', message: 'Weather location updated.' });
} catch (error) { } catch (error) {
try { await connection.rollback(); } catch (_rollbackError) { } try { await connection.rollback(); } catch (_rollbackError) { }
@@ -174,6 +179,7 @@ module.exports = function registerWeatherRoutes(app, deps) {
return res.redirect('/data-sources/weather/' + location.id + '/edit?message=' + encodeURIComponent('Weather location is disabled.')); return res.redirect('/data-sources/weather/' + location.id + '/edit?message=' + encodeURIComponent('Weather location is disabled.'));
} }
await backgroundTaskQueue.enqueueTask({ key: 'weather-location-refresh:' + location.id, title: 'Weather location refresh', category: 'data-source', taskType: 'data-source-refresh', payload: { sourceType: 'weather-location', sourceId: location.id, sourceName: location.name, actorId: getAuditUserId(req) }, metadata: { sourceType: 'weather-location', sourceId: location.id, sourceName: location.name } }); await backgroundTaskQueue.enqueueTask({ key: 'weather-location-refresh:' + location.id, title: 'Weather location refresh', category: 'data-source', taskType: 'data-source-refresh', payload: { sourceType: 'weather-location', sourceId: location.id, sourceName: location.name, actorId: getAuditUserId(req) }, metadata: { sourceType: 'weather-location', sourceId: location.id, sourceName: location.name } });
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'weather', eventType: 'weather-location.refresh_requested', actorUserId: getAuditUserId(req), targetType: 'weather-location', targetId: location.id, targetLabel: location.name });
res.redirect('/data-sources/weather/' + location.id + '/edit?message=' + encodeURIComponent('Weather refresh queued.')); res.redirect('/data-sources/weather/' + location.id + '/edit?message=' + encodeURIComponent('Weather refresh queued.'));
} catch (error) { next(error); } } catch (error) { next(error); }
}); });
@@ -187,6 +193,7 @@ module.exports = function registerWeatherRoutes(app, deps) {
} }
await pool.query('DELETE FROM i_weather_locations WHERE id = ?', [location.id]); await pool.query('DELETE FROM i_weather_locations WHERE id = ?', [location.id]);
dataSourceTasks.removeRecurringRefresh('weather-location', location.id); dataSourceTasks.removeRecurringRefresh('weather-location', location.id);
if (typeof recordRequestAuditEvent === 'function') await recordRequestAuditEvent(pool, req, { category: 'weather', eventType: 'weather-location.deleted', actorUserId: getAuditUserId(req), targetType: 'weather-location', targetId: location.id, targetLabel: location.name });
res.redirect('/data-sources/weather?message=' + encodeURIComponent('Weather location deleted.')); res.redirect('/data-sources/weather?message=' + encodeURIComponent('Weather location deleted.'));
} catch (error) { next(error); } } catch (error) { next(error); }
}); });

Some files were not shown because too many files have changed in this diff Show More