Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fea29f6a3c | ||
|
|
394d23bb4d | ||
|
|
0a03cdd0b7 | ||
|
|
bdb5ab4bac |
@@ -2,6 +2,38 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -29,10 +29,10 @@ For a complete installation, follow the [public stack setup](docker-compose/READ
|
||||
|
||||
## Docs
|
||||
|
||||
- [Documentation home](docs/README.md) - the technical reference index.
|
||||
- [API reference](docs/api.md) - the player HTTP surface and onboarding endpoints.
|
||||
- [Database schema](docs/schema.md) - the tables and data model the app maintains.
|
||||
- [WebSocket reference](docs/websocket.md) - the live player and snapshot channels.
|
||||
- [Documentation home](docs/README.md) - the index for user and technical guides.
|
||||
- [User guides](docs/user/README.md) - dashboard workflows, publishing, players, and Local Control.
|
||||
- [Technical guides](docs/technical/README.md) - API, database, and WebSocket references.
|
||||
- [Docker Compose guide](docker-compose/README.md) - deployment, service configuration, and remote-player setup.
|
||||
- [Changelog](CHANGELOG.md) - release history and notable changes.
|
||||
|
||||
## Explore The Docs
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pulse-signage-player",
|
||||
"version": "2.11.2",
|
||||
"version": "2.13.2",
|
||||
"private": false,
|
||||
"description": "Pulse Signage player application bundle",
|
||||
"engines": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pulse-signage-web",
|
||||
"version": "2.11.2",
|
||||
"version": "2.13.2",
|
||||
"private": false,
|
||||
"description": "Pulse Signage web and bridge application bundle",
|
||||
"engines": {
|
||||
|
||||
@@ -148,9 +148,9 @@ Important values:
|
||||
| `MYSQL_ROOT_PASSWORD` | Local MySQL root password. | `root_password` |
|
||||
| `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` |
|
||||
| `PLAYER_INTERNAL_URL` | Internal URL used for local player calls. | `http://player: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` |
|
||||
|
||||
+4
-5
@@ -1,14 +1,13 @@
|
||||
# Documentation
|
||||
|
||||
This folder contains the technical reference material for Pulse Signage.
|
||||
This folder contains user guides and technical references for Pulse Signage.
|
||||
|
||||
## What’s Here
|
||||
|
||||
- [API reference](api.md) - the player HTTP surface and onboarding endpoints.
|
||||
- [Database schema](schema.md) - the tables and data model used by the app.
|
||||
- [WebSocket reference](websocket.md) - the live player and snapshot channels.
|
||||
- [User guides](user/README.md) - using the dashboard, publishing content, operating players, and Local Control.
|
||||
- [Technical guides](technical/README.md) - API, database, and WebSocket references.
|
||||
- [Compose guide](../docker-compose/README.md) - Docker Compose deployment and service configuration.
|
||||
|
||||
## 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.
|
||||
@@ -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).
|
||||
@@ -82,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_template_regions` - template region layout and metadata.
|
||||
- `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_slide_schedule_rules` - rule rows attached to playlist slides.
|
||||
|
||||
@@ -115,6 +116,12 @@ Tables generally use a numeric auto-increment `id` primary key. The relationship
|
||||
- Foreign key:
|
||||
- `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`
|
||||
|
||||
- `id`, `playlist_id`, `slide_id`, `position`, `duration_seconds`, `use_video_duration`, `disable_audio`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
@@ -292,6 +299,8 @@ erDiagram
|
||||
}
|
||||
C_SLIDES {
|
||||
}
|
||||
C_MEDIA_ASSETS {
|
||||
}
|
||||
C_PLAYLIST_SLIDES {
|
||||
}
|
||||
C_PLAYLIST_SLIDE_SCHEDULE_RULES {
|
||||
@@ -339,6 +348,8 @@ erDiagram
|
||||
C_CANVAS_SIZES o|--o{ C_PLAYLISTS : used_by
|
||||
C_TEMPLATES ||--o{ C_TEMPLATE_REGIONS : contains
|
||||
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_SLIDES ||--o{ C_PLAYLIST_SLIDES : included_in
|
||||
C_PLAYLIST_SLIDES ||--o{ C_PLAYLIST_SLIDE_SCHEDULE_RULES : has_rules
|
||||
@@ -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).
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "pulse-signage",
|
||||
"version": "2.11.2",
|
||||
"version": "2.13.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pulse-signage",
|
||||
"version": "2.11.2",
|
||||
"version": "2.13.2",
|
||||
"dependencies": {
|
||||
"@sparticuz/chromium": "^149.0.0",
|
||||
"animate.css": "^4.1.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pulse-signage",
|
||||
"version": "2.11.2",
|
||||
"version": "2.13.2",
|
||||
"private": false,
|
||||
"description": "Pulse Signage application with MySQL and media storage",
|
||||
"engines": {
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
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_DIGEST = 'sha256';
|
||||
const SESSION_BYTES = 32;
|
||||
|
||||
+17
-2
@@ -101,7 +101,22 @@ function stripEditorOnlyMarkup(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) {
|
||||
@@ -507,7 +522,7 @@ async function buildTemplateContent(pool, template, body, filesByField, existing
|
||||
};
|
||||
}
|
||||
}
|
||||
return content;
|
||||
return normalizeEditorMediaReferences(content);
|
||||
}
|
||||
|
||||
async function buildSlidePayload(pool, req, existingSlide) {
|
||||
|
||||
@@ -103,6 +103,24 @@ async function ensureSchema(pool, options) {
|
||||
) 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(`
|
||||
CREATE TABLE IF NOT EXISTS c_playlist_slides (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
|
||||
@@ -621,6 +621,37 @@ const VERSIONED_MIGRATIONS = [
|
||||
) 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ const { createPlayerPlaylistService } = require('../player/playlist');
|
||||
const { commitDeviceBinding, bindPlayerToScreen, getOnboardingStatus, getPlayerPublicBaseUrl } = require('../player/onboarding');
|
||||
const { createStyledQrCodeSvg } = require('../data/qr-code');
|
||||
const { verifyPageAuthToken } = require('#src/request-auth');
|
||||
const { collectLocalControlUsers } = require('../web/lib/local-control-users');
|
||||
|
||||
|
||||
function createThinClientConfig() {
|
||||
@@ -186,6 +187,7 @@ async function start() {
|
||||
const server = http.createServer(app);
|
||||
const pool = common.createPool();
|
||||
const config = createThinClientConfig();
|
||||
const localPlayerInternalUrl = String(process.env.LOCAL_PLAYER_INTERNAL_URL || process.env.PLAYER_INTERNAL_URL || '').trim().replace(/\/$/, '');
|
||||
const playerPlaylistService = createPlayerPlaylistService({
|
||||
pool: pool,
|
||||
common: common,
|
||||
@@ -416,6 +418,18 @@ async function start() {
|
||||
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) {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||
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`);
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
|
||||
server.listen(config.port, function () {
|
||||
|
||||
@@ -17,6 +17,7 @@ const { ensureFontLibrary } = require('#src/web/lib/media/font-library');
|
||||
const { createRequestAuthHeaders } = require('#src/request-auth');
|
||||
const { withClientNameReservation } = require('#src/data/client-name-check');
|
||||
const { getConfiguredPlayerIdentifier, recordPlayerHeartbeat } = require('#src/data/player-registry');
|
||||
const { createLocalControlService } = require('./player/local-control');
|
||||
|
||||
|
||||
// Player runtime, media API, and websocket wiring.
|
||||
@@ -94,6 +95,15 @@ async function start() {
|
||||
const server = http.createServer(app);
|
||||
playerRuntime.installWebsocket(server);
|
||||
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;
|
||||
|
||||
@@ -364,6 +374,8 @@ async function start() {
|
||||
onPlayerPublicBaseUrl: setPlayerPublicBaseUrl
|
||||
});
|
||||
|
||||
await localControlService.loadCache();
|
||||
|
||||
function createThinClientWebSocketUrl() {
|
||||
if (!BRIDGE_PUBLIC_URL) {
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,583 @@
|
||||
// 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.use('/media/player-cache', function (_req, res) {
|
||||
return res.sendStatus(404);
|
||||
});
|
||||
|
||||
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 };
|
||||
+23
-1
@@ -32,6 +32,7 @@ function createPlayerRuntime(options) {
|
||||
const connectionsBySlug = new Map();
|
||||
const dashboardListenersBySlug = new Map();
|
||||
const announcementListenersBySlug = new Map();
|
||||
const snapshotListeners = new Set();
|
||||
const pendingCommandAcks = new Map();
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
const staleConnectionMs = Number(options && options.staleConnectionMs) > 0
|
||||
@@ -379,6 +380,12 @@ function createPlayerRuntime(options) {
|
||||
} catch (_error) {
|
||||
}
|
||||
}
|
||||
snapshotListeners.forEach(function (listener) {
|
||||
try {
|
||||
listener({ slug: key, connections: connections });
|
||||
} catch (_error) {
|
||||
}
|
||||
});
|
||||
if (!bucket || !bucket.size) {
|
||||
return;
|
||||
}
|
||||
@@ -503,6 +510,10 @@ function createPlayerRuntime(options) {
|
||||
const playerMatch = pathname.match(/^\/ws\/screens\/([^/]+)$/);
|
||||
const announcementMatch = pathname.match(/^\/ws\/screens\/([^/]+)\/announcements$/);
|
||||
|
||||
if (pathname === '/local-control/ws') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!dashboardMatch && !playerMatch && !announcementMatch) {
|
||||
socket.destroy();
|
||||
return;
|
||||
@@ -720,6 +731,16 @@ function createPlayerRuntime(options) {
|
||||
server.on('upgrade', handleUpgrade);
|
||||
}
|
||||
|
||||
function subscribeSnapshot(listener) {
|
||||
if (typeof listener !== 'function') {
|
||||
return function () {};
|
||||
}
|
||||
snapshotListeners.add(listener);
|
||||
return function () {
|
||||
snapshotListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
installWebsocket: installWebsocket,
|
||||
broadcastAnnouncementRefresh: broadcastAnnouncementRefresh,
|
||||
@@ -728,7 +749,8 @@ function createPlayerRuntime(options) {
|
||||
snapshotSlugs: snapshotSlugs,
|
||||
isClientNameAvailableOnScreen: isClientNameAvailableOnScreen,
|
||||
sendCommandToConnection: sendCommandToConnection,
|
||||
broadcastCommand: broadcastCommand
|
||||
broadcastCommand: broadcastCommand,
|
||||
subscribeSnapshot: subscribeSnapshot
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+10
@@ -81,6 +81,16 @@ const PERMISSION_SECTIONS = [
|
||||
{ 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',
|
||||
order: 50,
|
||||
|
||||
@@ -238,11 +238,13 @@ async function start() {
|
||||
backgroundTaskQueue: backgroundTaskQueue,
|
||||
webBootstrap: webBootstrap,
|
||||
notifyPlayerScreens: notifyPlayerScreens,
|
||||
forwardPlayerCommandToDevice: playerActionService.forwardPlayerCommandToDevice,
|
||||
loadCurrentUser: loadCurrentUser,
|
||||
initializeBackgroundTasks: initializeBackgroundTasks,
|
||||
captureSlideThumbnail: captureSlideThumbnail,
|
||||
server: server,
|
||||
webBaseUrl: webConfig.webInternalUrl,
|
||||
localPlayerInternalUrl: webConfig.playerInternalUrl,
|
||||
dataSourceStartupRefreshStaggerMs: webConfig.dataSourceStartupRefreshStaggerMs
|
||||
});
|
||||
|
||||
|
||||
@@ -172,6 +172,7 @@ function registerActionHelpers(Handlebars) {
|
||||
// Shared partials are registered once at startup.
|
||||
function registerPartials(Handlebars, viewsRoot) {
|
||||
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('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'));
|
||||
|
||||
@@ -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 };
|
||||
@@ -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 };
|
||||
@@ -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
|
||||
};
|
||||
@@ -253,10 +253,18 @@ function createUploadSyncService(options) {
|
||||
|
||||
function normalizeUploadReference(uploadPath) {
|
||||
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 value;
|
||||
}
|
||||
|
||||
function getUploadRelativePath(uploadPath) {
|
||||
@@ -313,6 +321,13 @@ function createUploadSyncService(options) {
|
||||
if (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;
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
async function removeUnusedUploadFiles(pool, uploadDir, uploadPaths) {
|
||||
const uniquePaths = Array.from(new Set((uploadPaths || []).map(normalizeUploadReference).filter(Boolean)));
|
||||
for (let i = 0; i < uniquePaths.length; i += 1) {
|
||||
const uploadPath = uniquePaths[i];
|
||||
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
|
||||
});
|
||||
async function uploadFileExists(uploadDir, uploadPath) {
|
||||
const filePath = resolveUploadFilePath(uploadDir, uploadPath);
|
||||
if (!filePath) {
|
||||
return false;
|
||||
}
|
||||
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) {
|
||||
@@ -981,6 +985,10 @@ function createUploadSyncService(options) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isLocalLikeBaseUrl(taskPayload.playerInternalBaseUrl) && await uploadFileExists(operation.localUploadDir, removedUploadRef)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const deleted = await removeUploadFileFromPlayer(removedUploadRef, operation.localUploadDir, taskPayload.playerInternalBaseUrl, taskPayload.playerIdentifier);
|
||||
if (!deleted) {
|
||||
queuePlayerUploadSync({
|
||||
|
||||
@@ -9,6 +9,8 @@ async function initializeWebServer(options) {
|
||||
const loadCurrentUser = options && options.loadCurrentUser;
|
||||
const initializeBackgroundTasks = options && options.initializeBackgroundTasks;
|
||||
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 server = options && options.server;
|
||||
|
||||
@@ -25,9 +27,11 @@ async function initializeWebServer(options) {
|
||||
common: common,
|
||||
backgroundTaskQueue: backgroundTaskQueue,
|
||||
notifyPlayerScreens: options && options.notifyPlayerScreens ? options.notifyPlayerScreens : null,
|
||||
forwardPlayerCommandToDevice: forwardPlayerCommandToDevice,
|
||||
uploadSyncService: webBootstrap.uploadSyncService,
|
||||
captureSlideThumbnail: captureSlideThumbnail,
|
||||
mediaDir: mediaDir,
|
||||
localPlayerInternalUrl: localPlayerInternalUrl,
|
||||
webBaseUrl: options && options.webBaseUrl ? options.webBaseUrl : null,
|
||||
dataSourceStartupRefreshStaggerMs: dataSourceStartupRefreshStaggerMs
|
||||
});
|
||||
|
||||
@@ -29,7 +29,7 @@ module.exports = function registerMiddleware(app, deps) {
|
||||
});
|
||||
|
||||
app.use(function (req, res, next) {
|
||||
if (req.path === '/' || req.path === '/login' || req.path === '/logout' || req.path === '/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') {
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ module.exports = {
|
||||
renderCanvasSizeAddPage: require(routePath('signage', 'canvas-sizes', 'add')),
|
||||
renderCanvasSizeEditPage: require(routePath('signage', 'canvas-sizes', 'edit')),
|
||||
renderFontsPage: require(routePath('settings', 'fonts', 'list')),
|
||||
renderMediaLibraryPage: require(routePath('settings', 'media-library', 'list')),
|
||||
renderBackgroundTasksPage: require(routePath('settings', 'background-tasks-page')).renderBackgroundTasksPage,
|
||||
renderBackgroundTasksScheduledPage: require(routePath('settings', 'background-tasks-page')).renderBackgroundTasksScheduledPage,
|
||||
renderErrorPage: require('./error'),
|
||||
|
||||
@@ -1,3 +1,293 @@
|
||||
.media-picker-item {
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: .375rem;
|
||||
background: var(--bs-body-bg);
|
||||
padding: .5rem;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.media-picker-item:hover,
|
||||
.media-picker-item:focus-visible {
|
||||
border-color: var(--bs-primary);
|
||||
box-shadow: 0 0 0 .15rem rgba(var(--bs-primary-rgb), .2);
|
||||
}
|
||||
|
||||
.media-picker-item-preview {
|
||||
display: block;
|
||||
aspect-ratio: 16 / 9;
|
||||
background: var(--bs-tertiary-bg);
|
||||
margin-bottom: .5rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.media-picker-item-preview img,
|
||||
.media-picker-item-preview video {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.media-gallery-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.media-gallery-count {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.media-gallery-search {
|
||||
width: min(100%, 52rem);
|
||||
}
|
||||
|
||||
.media-gallery-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: .75rem;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.media-gallery-bulk-actions {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
@media (min-width: 1200px) {
|
||||
.media-gallery-controls {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.media-gallery-search {
|
||||
width: auto;
|
||||
flex: 0 1 auto;
|
||||
flex-wrap: nowrap !important;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.media-gallery-search .input-group {
|
||||
min-width: 10rem;
|
||||
width: 28rem;
|
||||
max-width: 28rem;
|
||||
}
|
||||
}
|
||||
|
||||
.media-gallery-search .input-group {
|
||||
min-width: 15rem;
|
||||
flex: 1 1 18rem;
|
||||
}
|
||||
|
||||
.media-gallery-search .form-select {
|
||||
flex: 0 1 9rem;
|
||||
}
|
||||
|
||||
.media-gallery-card {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: .375rem;
|
||||
background: var(--bs-body-bg);
|
||||
box-shadow: 0 .125rem .25rem rgba(0, 0, 0, .04);
|
||||
}
|
||||
|
||||
.media-gallery-card-selected {
|
||||
border-color: var(--bs-primary);
|
||||
background: var(--bs-primary-bg-subtle);
|
||||
outline: 3px solid rgba(var(--bs-primary-rgb), .3);
|
||||
outline-offset: -3px;
|
||||
}
|
||||
|
||||
.media-gallery-card-selected::after {
|
||||
position: absolute;
|
||||
top: .65rem;
|
||||
right: .65rem;
|
||||
z-index: 2;
|
||||
padding: .25rem .5rem;
|
||||
border-radius: .25rem;
|
||||
background: var(--bs-primary);
|
||||
color: var(--bs-white);
|
||||
content: 'Selected';
|
||||
font-size: .75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.media-gallery-card-selection-disabled {
|
||||
opacity: .72;
|
||||
}
|
||||
|
||||
.media-gallery-card-selection-disabled::before {
|
||||
position: absolute;
|
||||
top: .65rem;
|
||||
left: .65rem;
|
||||
z-index: 2;
|
||||
padding: .25rem .5rem;
|
||||
border-radius: .25rem;
|
||||
background: var(--bs-secondary);
|
||||
color: var(--bs-white);
|
||||
content: 'In use';
|
||||
font-size: .75rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.media-gallery-selection-mode .media-gallery-card.media-gallery-card-selection-disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.media-gallery-selection-mode .media-gallery-card {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.media-gallery-preview {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
aspect-ratio: 4 / 3;
|
||||
overflow: hidden;
|
||||
background: var(--bs-tertiary-bg);
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.media-gallery-preview img,
|
||||
.media-gallery-preview video {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: transform .2s ease;
|
||||
}
|
||||
|
||||
.media-gallery-preview:hover img,
|
||||
.media-gallery-preview:hover video {
|
||||
transform: scale(1.03);
|
||||
}
|
||||
|
||||
.media-gallery-preview:focus-visible {
|
||||
outline: .2rem solid var(--bs-primary);
|
||||
outline-offset: -.2rem;
|
||||
}
|
||||
|
||||
.media-gallery-type {
|
||||
position: absolute;
|
||||
top: .75rem;
|
||||
left: .75rem;
|
||||
padding: .2rem .45rem;
|
||||
border-radius: .25rem;
|
||||
background: rgba(0, 0, 0, .65);
|
||||
color: #fff;
|
||||
font-size: .7rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: .04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.media-gallery-play {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
font-size: 2.5rem;
|
||||
text-shadow: 0 .1rem .35rem rgba(0, 0, 0, .55);
|
||||
}
|
||||
|
||||
.media-gallery-details {
|
||||
position: relative;
|
||||
padding: .6rem .75rem .75rem;
|
||||
}
|
||||
|
||||
.media-gallery-name {
|
||||
min-width: 0;
|
||||
min-height: 1.425rem;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
font-size: .95rem;
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
line-height: 1.425rem;
|
||||
}
|
||||
|
||||
.media-gallery-header {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
padding-right: 2.75rem;
|
||||
}
|
||||
|
||||
.media-gallery-action {
|
||||
position: absolute;
|
||||
right: .75rem;
|
||||
bottom: .75rem;
|
||||
}
|
||||
|
||||
.media-gallery-action button {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.media-gallery-meta {
|
||||
color: var(--bs-secondary-color);
|
||||
font-size: .8rem;
|
||||
}
|
||||
|
||||
.media-gallery-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: .75rem;
|
||||
}
|
||||
|
||||
.media-gallery-footer .media-gallery-meta {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.media-gallery-empty {
|
||||
padding: 3rem 1rem;
|
||||
border: 1px dashed var(--bs-border-color);
|
||||
border-radius: .375rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.media-gallery-controls {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.media-gallery-bulk-actions {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.media-gallery-search {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.media-gallery-search .input-group,
|
||||
.media-gallery-search .form-select {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.media-gallery-preview-modal-body {
|
||||
display: grid;
|
||||
min-height: min(70vh, 42rem);
|
||||
place-items: center;
|
||||
background: var(--bs-tertiary-bg);
|
||||
}
|
||||
|
||||
.media-gallery-preview-modal-body img,
|
||||
.media-gallery-preview-modal-body video {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: min(72vh, 48rem);
|
||||
object-fit: contain;
|
||||
}
|
||||
.status-dot {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
@@ -852,6 +1142,44 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.media-library-page {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.media-library-page .app-wrapper {
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.media-library-page .app-main {
|
||||
padding-bottom: 0;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden !important;
|
||||
}
|
||||
|
||||
.media-library-page .app-content {
|
||||
flex: 1 1 0;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.media-library-page .app-content .container-fluid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.media-library-page .media-gallery {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
[data-table-pagination-card] {
|
||||
display: flex;
|
||||
flex: 0 1 auto;
|
||||
@@ -2164,8 +2492,8 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
}
|
||||
|
||||
.slide-image-cropper-frame.is-loading > :not(.slide-image-cropper-loading-overlay) {
|
||||
opacity: 0.22;
|
||||
filter: saturate(0.8);
|
||||
visibility: hidden;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.slide-image-cropper-loading-overlay {
|
||||
@@ -2365,6 +2693,56 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.media-library-upload-zone {
|
||||
min-height: 132px;
|
||||
padding: 2rem 2.5rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.media-library-upload-zone .slide-image-region-upload-zone-limit {
|
||||
color: var(--bs-body-color);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.media-picker-toolbar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 12rem auto;
|
||||
gap: 0.75rem;
|
||||
background: var(--bs-modal-bg);
|
||||
}
|
||||
|
||||
#media-picker-modal .modal-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#media-picker-modal .media-picker-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
|
||||
#media-picker-modal [data-media-picker-no-results]:not([hidden]) {
|
||||
display: block;
|
||||
min-height: 4rem;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.media-picker-toolbar {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.media-picker-toolbar .btn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.slide-image-region-preview {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -3670,4 +4048,56 @@ table.table thead th.sort-desc .table-sort-indicator {
|
||||
|
||||
.gradient-stop-handle:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.media-picker-item-selected-card .media-picker-item {
|
||||
border-color: var(--bs-success);
|
||||
box-shadow: 0 0 0 .15rem rgba(var(--bs-success-rgb), .2);
|
||||
}
|
||||
|
||||
.media-picker-item-statuses {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: .5rem;
|
||||
margin-top: .35rem;
|
||||
min-height: 1.2rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.media-picker-item-statuses [hidden] {
|
||||
display: inline;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.media-picker-item-selected {
|
||||
color: var(--bs-success-text-emphasis, var(--bs-success));
|
||||
font-size: .8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.media-picker-item-current {
|
||||
color: var(--bs-info-text-emphasis, var(--bs-info));
|
||||
font-size: .8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.modal-dialog.modal-xxl {
|
||||
width: calc(100% - 2rem);
|
||||
max-width: 1440px;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.modal-dialog.modal-xxl {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.media-gallery-scroll {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
max-height: none;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding-right: .5rem;
|
||||
padding-bottom: 1rem;
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// 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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
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 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 = '';
|
||||
});
|
||||
})();
|
||||
@@ -41,12 +41,12 @@
|
||||
bodyHtml: '' +
|
||||
'<div class="row g-3 align-items-start">' +
|
||||
'<div class="col-12 col-md-8 d-flex flex-column">' +
|
||||
'<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" for="region_image_' + region.id + '">' +
|
||||
'<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" />' +
|
||||
'<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-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 class="slide-image-region-upload-zone-limit">Max ' + escapeHtml(uploadMaxLabel) + ' per file</span>' +
|
||||
'</span>' +
|
||||
|
||||
@@ -982,12 +982,12 @@
|
||||
var imageOptionsHtml = '' +
|
||||
'<div class="row g-3 align-items-start">' +
|
||||
'<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/*" />' +
|
||||
'<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-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 class="slide-image-region-upload-zone-limit">Replaces the QR image logo</span>' +
|
||||
'</span>' +
|
||||
|
||||
@@ -46,12 +46,12 @@
|
||||
bodyHtml: '' +
|
||||
'<div class="row g-3 align-items-start">' +
|
||||
'<div class="col-12 col-md-8 d-flex flex-column">' +
|
||||
'<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" for="region_video_' + region.id + '">' +
|
||||
'<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) + '" />' +
|
||||
'<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-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 class="slide-image-region-upload-zone-limit">Max ' + escapeHtml(uploadVideoMaxLabel) + ' per file</span>' +
|
||||
'</span>' +
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export function createSlideFormRegionHelpers(options) {
|
||||
var apiSources = Array.isArray(settings.apiSources) ? settings.apiSources : [];
|
||||
var timetableGroups = Array.isArray(settings.timetableGroups) ? settings.timetableGroups : [];
|
||||
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 requestPreviewRender = typeof settings.requestPreviewRender === 'function' ? settings.requestPreviewRender : function () {};
|
||||
var placeholderUtils = window.placeholderUtils || {};
|
||||
@@ -570,7 +571,8 @@ export function createSlideFormRegionHelpers(options) {
|
||||
: [],
|
||||
sampleDataPreview: buildApiSampleDataMarkup(getCurrentApiConfig(region).source_id, getCurrentApiConfig(region).item_number, getCurrentApiConfig(region).items_path),
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -612,7 +614,8 @@ export function createSlideFormRegionHelpers(options) {
|
||||
: [],
|
||||
sampleDataPreview: buildApiSampleDataMarkup(apiConfig.source_id, apiConfig.item_number, apiItemsPath),
|
||||
timetableGroups: timetableGroups,
|
||||
weatherLocations: weatherLocations
|
||||
weatherLocations: weatherLocations,
|
||||
mediaAssets: mediaAssets
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -169,6 +169,7 @@ import { createSlideFormPreviewHelpers } from '/assets/js/slides/slide-form-prev
|
||||
apiSources: apiSources,
|
||||
timetableGroups: timetableGroups,
|
||||
weatherLocations: weatherLocations,
|
||||
mediaAssets: Array.isArray(slideEditorData.mediaAssets) ? slideEditorData.mediaAssets : [],
|
||||
defaultFontSize: DEFAULT_FONT_SIZE,
|
||||
uploadMaxLabel: uploadMaxLabel,
|
||||
uploadVideoMaxLabel: uploadVideoMaxLabel,
|
||||
@@ -927,7 +928,7 @@ import { createSlideFormPreviewHelpers } from '/assets/js/slides/slide-form-prev
|
||||
}
|
||||
|
||||
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_"]');
|
||||
if (webpageInput) {
|
||||
templateSelectorLock.arm();
|
||||
|
||||
@@ -1776,16 +1776,25 @@
|
||||
|
||||
renderAddRegionOptions();
|
||||
}
|
||||
backgroundInput.addEventListener('change', function () {
|
||||
var file = backgroundInput.files && backgroundInput.files[0];
|
||||
if (file) {
|
||||
updateBackgroundPreview(file);
|
||||
}
|
||||
});
|
||||
if (backgroundInput) {
|
||||
backgroundInput.addEventListener('change', function () {
|
||||
var file = backgroundInput.files && backgroundInput.files[0];
|
||||
if (file) {
|
||||
updateBackgroundPreview(file);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (removeBackgroundButton && removeBackgroundFlag) {
|
||||
removeBackgroundButton.addEventListener('click', function () {
|
||||
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.style.display = 'none';
|
||||
backgroundEmpty.style.display = 'block';
|
||||
|
||||
@@ -7,6 +7,7 @@ const { fetchAppSettings } = require('#src/data/app-settings');
|
||||
const { convertWeatherSnapshot } = require('#src/data/weather-units');
|
||||
const { buildAuditChanges } = require('#src/data/audit-log');
|
||||
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) {
|
||||
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 weatherData = typeof common.fetchWeatherLocationsData === 'function' ? await common.fetchWeatherLocationsData(pool) : { weatherLocations: [] };
|
||||
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) {
|
||||
return Object.assign({}, source, {
|
||||
responseJson: typeof common.parseJsonSafe === 'function' ? common.parseJsonSafe(source.last_response_json) : null
|
||||
@@ -92,6 +95,7 @@ module.exports = function registerContentRoutes(app, deps) {
|
||||
apiSources: apiSources,
|
||||
timetableGroups: timetableData.timetableGroups || [],
|
||||
weatherLocations: weatherLocations,
|
||||
mediaAssets: mediaAssets,
|
||||
fontLibrary: loadFontLibrary(deps.uploadDir),
|
||||
uploadLimits: {
|
||||
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();
|
||||
|
||||
await validateUploadedFiles([req.file], uploadContext);
|
||||
await registerMediaAssets(pool, [req.file], function (file) {
|
||||
return '/media/uploads/' + file.filename;
|
||||
}, getUploadedFileMediaType, getAuditUserId(req), { published: false });
|
||||
|
||||
res.json({
|
||||
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.' });
|
||||
}
|
||||
|
||||
await removeUnusedUploadFiles(pool, deps.uploadDir, uploadPaths);
|
||||
await removePendingMediaAssets(pool, deps.uploadDir, uploadPaths);
|
||||
res.sendStatus(204);
|
||||
} catch (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) {
|
||||
try {
|
||||
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);
|
||||
if (await common.fetchDuplicateName(pool, 'c_slides', payload.title, null, 'title')) {
|
||||
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 (?, ?, ?, ?, ?)',
|
||||
[payload.title, payload.templateId, payload.contentJson, actorId, actorId]
|
||||
);
|
||||
await publishMediaAssets(pool, collectUploadReferencesFromPayload(payload));
|
||||
await syncPlaylistUploadsOnChange({
|
||||
key: 'slide:create:' + result.insertId,
|
||||
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) {
|
||||
try {
|
||||
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));
|
||||
if (!slide) {
|
||||
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 = ?',
|
||||
[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({
|
||||
key: 'slide:update:' + slide.id,
|
||||
pool: pool,
|
||||
@@ -615,7 +630,9 @@ module.exports = function registerContentRoutes(app, deps) {
|
||||
app.get('/templates/new', requirePermission('templates.create'), async function (req, res, next) {
|
||||
try {
|
||||
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) {
|
||||
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) {
|
||||
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);
|
||||
if (!payload.regions.length) {
|
||||
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.inUse = (await fetchSlidesByTemplateId(template.id)).length > 0;
|
||||
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) {
|
||||
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) {
|
||||
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));
|
||||
if (!template) {
|
||||
return res.status(404).send('Template not found');
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Internal sync trigger routes for player-driven queue flushes.
|
||||
// Internal synchronization routes owned by the web service.
|
||||
|
||||
const { verifyRequestAuth } = require('#src/request-auth');
|
||||
const { collectFontLibrarySyncOperations } = require('#src/web/lib/media/font-library');
|
||||
const { collectLocalControlUsers } = require('../../lib/local-control-users');
|
||||
|
||||
function requireRequestAuth(req, res, next) {
|
||||
if (!verifyRequestAuth(req)) {
|
||||
@@ -15,6 +16,7 @@ module.exports = function registerInternalSyncRoutes(app, deps) {
|
||||
const backgroundTaskQueue = deps && deps.backgroundTaskQueue;
|
||||
const uploadSyncService = deps && deps.uploadSyncService;
|
||||
const mediaDir = String(deps && deps.mediaDir || '').trim();
|
||||
const pool = deps && deps.pool;
|
||||
|
||||
if (!backgroundTaskQueue || typeof backgroundTaskQueue.enqueueTask !== 'function' || !uploadSyncService || !mediaDir) {
|
||||
throw new Error('registerInternalSyncRoutes requires the sync dependencies.');
|
||||
@@ -87,4 +89,19 @@ module.exports = function registerInternalSyncRoutes(app, deps) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/internal/sync/player-control', requireRequestAuth, async function (_req, res, next) {
|
||||
try {
|
||||
if (!pool) {
|
||||
return res.status(503).json({ error: 'Player control sync is unavailable.' });
|
||||
}
|
||||
const users = await collectLocalControlUsers(pool);
|
||||
res.json({
|
||||
users: users,
|
||||
syncedAt: new Date().toISOString()
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -16,6 +16,7 @@ const registerTimetableRoutes = require('./data-sources/timetables/routes');
|
||||
const registerWeatherRoutes = require('./data-sources/weather');
|
||||
const registerSettingsRoutes = require('./settings/background-tasks');
|
||||
const registerFontRoutes = require('./settings/fonts');
|
||||
const registerMediaLibraryRoutes = require('./settings/media-library');
|
||||
const registerSettingsPageRoutes = require('./settings/routes');
|
||||
const registerAuditLogRoutes = require('./settings/audit-log');
|
||||
const registerAboutRoutes = require('./settings/about/routes');
|
||||
@@ -50,6 +51,7 @@ function registerRoutes(app, deps) {
|
||||
});
|
||||
registerAboutRoutes(app, deps);
|
||||
registerInternalSyncRoutes(app, {
|
||||
pool: deps.pool,
|
||||
backgroundTaskQueue: deps.backgroundTaskQueue,
|
||||
uploadSyncService: deps.uploadSyncService,
|
||||
mediaDir: deps.mediaDir
|
||||
@@ -332,6 +334,17 @@ function registerSettingsAndContentRoutes(app, deps) {
|
||||
setAuthMessageCookie: deps.setAuthMessageCookie,
|
||||
requirePermission: deps.requirePermission
|
||||
});
|
||||
|
||||
registerMediaLibraryRoutes(app, {
|
||||
pool: deps.pool,
|
||||
pages: deps.pages,
|
||||
upload: deps.upload,
|
||||
uploadDir: deps.uploadDir,
|
||||
getAuditUserId: deps.getAuditUserId,
|
||||
setAuthMessageCookie: deps.setAuthMessageCookie,
|
||||
requirePermission: deps.requirePermission,
|
||||
syncPlaylistUploadsOnChange: deps.syncPlaylistUploadsOnChange
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { registerRoutes };
|
||||
@@ -0,0 +1,276 @@
|
||||
// Shared media library routes.
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { fetchAppSettings } = require('#src/data/app-settings');
|
||||
const { hasAnyPermission, hasPermission, PERMISSION_DENIED_MESSAGE } = require('#src/rbac');
|
||||
const mediaLibrary = require('#src/web/lib/media/library');
|
||||
|
||||
function requireMediaAccess(setAuthMessageCookie) {
|
||||
return function (req, res, next) {
|
||||
if (!req.currentUser) {
|
||||
if (typeof setAuthMessageCookie === 'function') {
|
||||
setAuthMessageCookie(res, 'Please sign in to continue.');
|
||||
}
|
||||
return res.redirect('/login');
|
||||
}
|
||||
if (hasAnyPermission(req.currentUser, ['media-library.read', 'media-library.create', 'media-library.delete'])) {
|
||||
return next();
|
||||
}
|
||||
const error = new Error(PERMISSION_DENIED_MESSAGE);
|
||||
error.statusCode = 403;
|
||||
error.expose = true;
|
||||
next(error);
|
||||
};
|
||||
}
|
||||
|
||||
function getMediaType(file) {
|
||||
const mimeType = String(file && file.mimetype || '').toLowerCase();
|
||||
if (mimeType.indexOf('video/') === 0) {
|
||||
return 'video';
|
||||
}
|
||||
if (mimeType.indexOf('image/') === 0) {
|
||||
return 'image';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getUploadLimits(settings) {
|
||||
const imageMaxBytes = Number(settings && settings['uploads.image_max_bytes']) || 100 * 1024 * 1024;
|
||||
const videoMaxBytes = Number(settings && settings['uploads.video_max_bytes']) || 1024 * 1024 * 1024;
|
||||
const formatBytes = function (bytes) {
|
||||
const megabytes = bytes / 1024 / 1024;
|
||||
if (megabytes >= 1024 && megabytes % 1024 === 0) {
|
||||
return (megabytes / 1024) + ' GB';
|
||||
}
|
||||
return (Number.isInteger(megabytes) ? megabytes : megabytes.toFixed(2).replace(/0+$/, '').replace(/\.$/, '')) + ' MB';
|
||||
};
|
||||
return {
|
||||
imageMaxBytes: imageMaxBytes,
|
||||
videoMaxBytes: videoMaxBytes,
|
||||
imageMaxLabel: formatBytes(imageMaxBytes),
|
||||
videoMaxLabel: formatBytes(videoMaxBytes),
|
||||
allowedMimeTypes: Array.isArray(settings && settings['uploads.allowed_mime_types']) ? settings['uploads.allowed_mime_types'] : []
|
||||
};
|
||||
}
|
||||
|
||||
function formatFileSize(bytes) {
|
||||
const value = Number(bytes) || 0;
|
||||
if (value < 1024) {
|
||||
return value + ' B';
|
||||
}
|
||||
const units = ['KB', 'MB', 'GB', 'TB'];
|
||||
let size = value;
|
||||
let unitIndex = -1;
|
||||
while (size >= 1024 && unitIndex < units.length - 1) {
|
||||
size /= 1024;
|
||||
unitIndex += 1;
|
||||
}
|
||||
const precision = size >= 10 ? 0 : 1;
|
||||
return size.toFixed(precision).replace(/\.0$/, '') + ' ' + units[unitIndex];
|
||||
}
|
||||
|
||||
function getMediaFormat(asset) {
|
||||
const name = String(asset && (asset.original_name || asset.media_path) || '').trim();
|
||||
const match = name.match(/\.([a-z0-9]+)$/i);
|
||||
return match ? match[1].toUpperCase() : String(asset && asset.media_type || '').toUpperCase();
|
||||
}
|
||||
|
||||
function getAssetQuery(query) {
|
||||
const source = query || {};
|
||||
const sort = ['date-desc', 'date-asc', 'name-asc', 'name-desc', 'size-asc', 'size-desc'].includes(String(source.sort || ''))
|
||||
? String(source.sort)
|
||||
: 'date-desc';
|
||||
const type = ['image', 'video'].includes(String(source.type || '')) ? String(source.type) : 'all';
|
||||
const usage = ['used', 'unused'].includes(String(source.usage || '')) ? String(source.usage) : 'all';
|
||||
return {
|
||||
search: String(source.search || '').trim().toLowerCase(),
|
||||
type: type,
|
||||
usage: usage,
|
||||
sort: sort
|
||||
};
|
||||
}
|
||||
|
||||
function filterAndSortAssets(assets, query) {
|
||||
const filtered = assets.filter(function (asset) {
|
||||
const matchesSearch = !query.search || String(asset.original_name || '').toLowerCase().includes(query.search);
|
||||
const matchesType = query.type === 'all' || asset.media_type === query.type;
|
||||
const isUsed = Boolean(asset.inUse);
|
||||
const matchesUsage = query.usage === 'all' || (query.usage === 'used' ? isUsed : !isUsed);
|
||||
return matchesSearch && matchesType && matchesUsage;
|
||||
});
|
||||
filtered.sort(function (left, right) {
|
||||
const leftName = String(left.original_name || '').toLowerCase();
|
||||
const rightName = String(right.original_name || '').toLowerCase();
|
||||
const leftDate = String(left.created_at || '');
|
||||
const rightDate = String(right.created_at || '');
|
||||
if (query.sort === 'name-asc' || query.sort === 'name-desc') {
|
||||
return (query.sort === 'name-asc' ? 1 : -1) * leftName.localeCompare(rightName);
|
||||
}
|
||||
if (query.sort === 'size-asc' || query.sort === 'size-desc') {
|
||||
return (query.sort === 'size-asc' ? 1 : -1) * (Number(left.file_size) - Number(right.file_size));
|
||||
}
|
||||
return (query.sort === 'date-asc' ? 1 : -1) * leftDate.localeCompare(rightDate);
|
||||
});
|
||||
return filtered;
|
||||
}
|
||||
|
||||
module.exports = function registerMediaLibraryRoutes(app, deps) {
|
||||
const requireAccess = requireMediaAccess(deps.setAuthMessageCookie);
|
||||
const pageSize = 24;
|
||||
if (!deps.pool || !deps.pages || !deps.upload || !deps.uploadDir) {
|
||||
throw new Error('registerMediaLibraryRoutes requires pool, pages, upload, and uploadDir.');
|
||||
}
|
||||
|
||||
app.get('/media-library', requireAccess, deps.requirePermission('media-library.read'), async function (req, res, next) {
|
||||
try {
|
||||
await mediaLibrary.syncMediaAssetsFromDirectory(deps.pool, deps.uploadDir);
|
||||
const allAssets = await mediaLibrary.fetchMediaAssets(deps.pool);
|
||||
const usage = await Promise.all(allAssets.map(function (asset) {
|
||||
return mediaLibrary.countMediaAssetReferences(deps.pool, asset.media_path);
|
||||
}));
|
||||
allAssets.forEach(function (asset, index) {
|
||||
asset.referenceCount = usage[index];
|
||||
asset.inUse = usage[index] > 0;
|
||||
asset.displayFileSize = formatFileSize(asset.file_size);
|
||||
asset.mediaFormat = getMediaFormat(asset);
|
||||
asset.canDelete = hasPermission(req.currentUser, 'media-library.delete');
|
||||
});
|
||||
const settings = await fetchAppSettings(deps.pool);
|
||||
const filteredAssets = filterAndSortAssets(allAssets, getAssetQuery(req.query));
|
||||
res.send(deps.pages.renderMediaLibraryPage({
|
||||
assets: filteredAssets.slice(0, pageSize),
|
||||
assetTotal: filteredAssets.length,
|
||||
hasMore: filteredAssets.length > pageSize,
|
||||
uploadLimits: getUploadLimits(settings)
|
||||
}, req.query.message ? String(req.query.message) : '', req.currentUser));
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/media-library/assets', requireAccess, deps.requirePermission('media-library.read'), async function (req, res, next) {
|
||||
try {
|
||||
await mediaLibrary.syncMediaAssetsFromDirectory(deps.pool, deps.uploadDir);
|
||||
const allAssets = await mediaLibrary.fetchMediaAssets(deps.pool);
|
||||
const usage = await Promise.all(allAssets.map(function (asset) {
|
||||
return mediaLibrary.countMediaAssetReferences(deps.pool, asset.media_path);
|
||||
}));
|
||||
allAssets.forEach(function (asset, index) {
|
||||
asset.referenceCount = usage[index];
|
||||
asset.inUse = usage[index] > 0;
|
||||
asset.displayFileSize = formatFileSize(asset.file_size);
|
||||
asset.mediaFormat = getMediaFormat(asset);
|
||||
asset.canDelete = hasPermission(req.currentUser, 'media-library.delete');
|
||||
});
|
||||
const offset = Math.max(0, Number.parseInt(req.query.offset, 10) || 0);
|
||||
const limit = Math.min(pageSize, Math.max(1, Number.parseInt(req.query.limit, 10) || pageSize));
|
||||
const filteredAssets = filterAndSortAssets(allAssets, getAssetQuery(req.query));
|
||||
const assets = filteredAssets.slice(offset, offset + limit);
|
||||
res.json({ assets: assets, total: filteredAssets.length, nextOffset: offset + assets.length, hasMore: offset + assets.length < filteredAssets.length });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/media-library', requireAccess, deps.requirePermission('media-library.create'), deps.upload.single('file'), async function (req, res, next) {
|
||||
try {
|
||||
if (!req.file) {
|
||||
return res.redirect('/media-library?message=' + encodeURIComponent('Choose an image or video to upload.'));
|
||||
}
|
||||
const mediaType = getMediaType(req.file);
|
||||
const settings = await fetchAppSettings(deps.pool);
|
||||
const uploadLimits = getUploadLimits(settings);
|
||||
const mimeType = String(req.file.mimetype || '').trim().toLowerCase();
|
||||
const allowedMimeTypes = uploadLimits.allowedMimeTypes;
|
||||
const maxBytes = mediaType === 'video' ? uploadLimits.videoMaxBytes : uploadLimits.imageMaxBytes;
|
||||
if (allowedMimeTypes.indexOf(mimeType) === -1 || (mediaType !== 'image' && mediaType !== 'video')) {
|
||||
await fs.promises.unlink(req.file.path).catch(function () {});
|
||||
return res.redirect('/media-library?message=' + encodeURIComponent('This media type is disabled in Media Uploads settings.'));
|
||||
}
|
||||
if (Number(req.file.size || 0) > maxBytes) {
|
||||
await fs.promises.unlink(req.file.path).catch(function () {});
|
||||
const limitLabel = maxBytes >= 1024 * 1024 * 1024 && maxBytes % (1024 * 1024 * 1024) === 0
|
||||
? (maxBytes / (1024 * 1024 * 1024)) + ' GB'
|
||||
: Math.round(maxBytes / (1024 * 1024)) + ' MB';
|
||||
return res.redirect('/media-library?message=' + encodeURIComponent('File must be ' + limitLabel + ' or smaller.'));
|
||||
}
|
||||
await mediaLibrary.registerMediaAsset(deps.pool, Object.assign({}, req.file, { mediaType: mediaType }), '/media/uploads/' + req.file.filename, deps.getAuditUserId(req));
|
||||
res.redirect('/media-library?message=' + encodeURIComponent('Media uploaded.'));
|
||||
} catch (error) {
|
||||
if (req.file && req.file.path) {
|
||||
await fs.promises.unlink(req.file.path).catch(function () {});
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
async function deleteMediaAsset(assetId) {
|
||||
const [rows] = await deps.pool.query('SELECT id, media_path FROM c_media_assets WHERE id = ?', [Number(assetId)]);
|
||||
const asset = rows && rows[0];
|
||||
if (!asset) {
|
||||
return 'missing';
|
||||
}
|
||||
const referenceCount = await mediaLibrary.countMediaAssetReferences(deps.pool, asset.media_path);
|
||||
if (referenceCount > 0) {
|
||||
return 'in-use';
|
||||
}
|
||||
const filePath = path.join(path.dirname(deps.uploadDir), asset.media_path.replace(/^\/media\//, ''));
|
||||
await deps.pool.query('DELETE FROM c_media_assets WHERE id = ?', [asset.id]);
|
||||
await fs.promises.unlink(filePath).catch(function (error) {
|
||||
if (error && error.code !== 'ENOENT') {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
if (typeof deps.syncPlaylistUploadsOnChange === 'function') {
|
||||
await deps.syncPlaylistUploadsOnChange({
|
||||
key: 'media-library:delete:' + asset.id,
|
||||
pool: deps.pool,
|
||||
localUploadDir: deps.uploadDir,
|
||||
previousUploadRefs: [asset.media_path],
|
||||
nextUploadRefs: []
|
||||
});
|
||||
}
|
||||
return 'deleted';
|
||||
}
|
||||
|
||||
app.post('/media-library/delete', requireAccess, deps.requirePermission('media-library.delete'), async function (req, res, next) {
|
||||
try {
|
||||
const rawAssetIds = req.body && (req.body.assetIds || req.body['assetIds[]']);
|
||||
const assetIds = Array.from(new Set((Array.isArray(rawAssetIds) ? rawAssetIds : [rawAssetIds]).map(function (value) {
|
||||
return Number(value);
|
||||
}).filter(function (value) {
|
||||
return Number.isInteger(value) && value > 0;
|
||||
})));
|
||||
if (!assetIds.length) {
|
||||
return res.redirect('/media-library?message=' + encodeURIComponent('Select at least one media asset.'));
|
||||
}
|
||||
let deletedCount = 0;
|
||||
let inUseCount = 0;
|
||||
for (let index = 0; index < assetIds.length; index += 1) {
|
||||
const result = await deleteMediaAsset(assetIds[index]);
|
||||
if (result === 'deleted') deletedCount += 1;
|
||||
if (result === 'in-use') inUseCount += 1;
|
||||
}
|
||||
const message = deletedCount + ' media asset' + (deletedCount === 1 ? '' : 's') + ' deleted.' + (inUseCount ? ' ' + inUseCount + ' in-use asset' + (inUseCount === 1 ? '' : 's') + ' skipped.' : '');
|
||||
res.redirect('/media-library?message=' + encodeURIComponent(message));
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/media-library/:id/delete', requireAccess, deps.requirePermission('media-library.delete'), async function (req, res, next) {
|
||||
try {
|
||||
const result = await deleteMediaAsset(req.params.id);
|
||||
if (result === 'missing') {
|
||||
return res.redirect('/media-library?message=' + encodeURIComponent('Media asset not found.'));
|
||||
}
|
||||
if (result === 'in-use') {
|
||||
return res.redirect('/media-library?message=' + encodeURIComponent('This media is still used and cannot be deleted.'));
|
||||
}
|
||||
res.redirect('/media-library?message=' + encodeURIComponent('Media deleted.'));
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
// Media library page renderer.
|
||||
|
||||
const { renderView } = require('../../../view');
|
||||
|
||||
module.exports = function renderMediaLibraryPage(data, message, currentUser) {
|
||||
return renderView('settings/media-library/list', {
|
||||
title: 'Media library',
|
||||
active: 'media-library',
|
||||
bodyClass: 'media-library-page',
|
||||
message: message,
|
||||
currentUser: currentUser || null,
|
||||
assets: data.assets || [],
|
||||
assetTotal: Number(data.assetTotal || (data.assets || []).length),
|
||||
hasMore: Boolean(data.hasMore),
|
||||
uploadLimits: data.uploadLimits || {}
|
||||
});
|
||||
};
|
||||
@@ -28,6 +28,7 @@ function buildSlideFormViewModel(data, slide, message, currentUser, isEdit) {
|
||||
const weatherLocations = data && data.weatherLocations ? data.weatherLocations : [];
|
||||
const fontLibrary = data && data.fontLibrary ? data.fontLibrary : null;
|
||||
const uploadLimits = data && data.uploadLimits ? data.uploadLimits : {};
|
||||
const mediaAssets = Array.isArray(data && data.mediaAssets) ? data.mediaAssets : [];
|
||||
const templates = buildTemplates(data && data.templates ? data.templates : [], templateRegions);
|
||||
const viewSlide = slide || buildDefaultSlide();
|
||||
|
||||
@@ -54,7 +55,8 @@ function buildSlideFormViewModel(data, slide, message, currentUser, isEdit) {
|
||||
fontFamilyFormats: fontLibrary && fontLibrary.fontFamilyFormats ? fontLibrary.fontFamilyFormats : '',
|
||||
existingTemplateId: viewSlide && viewSlide.template_id ? viewSlide.template_id : null,
|
||||
existingContent: viewSlide && viewSlide.content ? viewSlide.content : {},
|
||||
uploadLimits: uploadLimits
|
||||
uploadLimits: uploadLimits,
|
||||
mediaAssets: mediaAssets
|
||||
},
|
||||
assetVersion: assetVersion,
|
||||
slideEditorScripts: ['vendor/qr-code-styling/qr-code-styling-loader.js?v=' + assetVersion].concat(getRegionEditorScripts(assetVersion)),
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
const { renderView } = require('../../../view');
|
||||
const { buildTemplateFormViewModel } = require('./form-view-model');
|
||||
|
||||
module.exports = function renderTemplateAddPage(template, message, canvasSizes, currentUser) {
|
||||
return renderView('templates/form', buildTemplateFormViewModel(template, message, canvasSizes, currentUser, false));
|
||||
module.exports = function renderTemplateAddPage(template, message, canvasSizes, currentUser, mediaAssets) {
|
||||
return renderView('templates/form', buildTemplateFormViewModel(template, message, canvasSizes, currentUser, false, mediaAssets));
|
||||
};
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
const { renderView } = require('../../../view');
|
||||
const { buildTemplateFormViewModel } = require('./form-view-model');
|
||||
|
||||
module.exports = function renderTemplateEditPage(template, data, message, currentUser) {
|
||||
return renderView('templates/form', buildTemplateFormViewModel(template, message, data && data.canvasSizes ? data.canvasSizes : [], currentUser, true));
|
||||
module.exports = function renderTemplateEditPage(template, data, message, currentUser, mediaAssets) {
|
||||
return renderView('templates/form', buildTemplateFormViewModel(template, message, data && data.canvasSizes ? data.canvasSizes : [], currentUser, true, mediaAssets));
|
||||
};
|
||||
|
||||
@@ -43,7 +43,7 @@ function resolveTemplateCanvasSize(template, canvasSizes) {
|
||||
});
|
||||
}
|
||||
|
||||
function buildTemplateFormViewModel(template, message, canvasSizes, currentUser, isEdit) {
|
||||
function buildTemplateFormViewModel(template, message, canvasSizes, currentUser, isEdit, mediaAssets) {
|
||||
const current = resolveTemplateCanvasSize(template || buildDefaultTemplate(), canvasSizes || []);
|
||||
const assetVersion = Date.now().toString(36);
|
||||
|
||||
@@ -64,6 +64,7 @@ function buildTemplateFormViewModel(template, message, canvasSizes, currentUser,
|
||||
deleteUrl: isEdit && current.id ? '/templates/' + current.id + '/delete' : '',
|
||||
deleteConfirmMessage: isEdit ? 'Delete this template?' : '',
|
||||
canvasSizes: canvasSizes || [],
|
||||
mediaAssets: Array.isArray(mediaAssets) ? mediaAssets : [],
|
||||
animationPresets: animationPresets,
|
||||
scripts: ['js/lib/modal.js?v=' + assetVersion, 'js/templates/animation-presets.js?v=' + assetVersion, 'vendor/qr-code-styling/qr-code-styling-loader.js?v=' + assetVersion].concat(getRegionEditorScripts(assetVersion), ['js/templates/template-designer-utils.js?v=' + assetVersion, 'js/templates/template-designer.js?v=' + assetVersion])
|
||||
};
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{#if stylesheetHref}}
|
||||
<link rel="stylesheet" href="{{stylesheetHref}}" />
|
||||
{{/if}}
|
||||
|
||||
<div class="card card-outline card-primary mb-4">
|
||||
<div class="card-header">
|
||||
<h3 class="card-title">Upload font</h3>
|
||||
@@ -47,6 +51,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-table-sort-key="family">Family</th>
|
||||
<th>Preview</th>
|
||||
<th data-table-sort-key="file">File</th>
|
||||
<th data-table-sort-key="format">Format</th>
|
||||
<th data-table-sort-key="status">Status</th>
|
||||
@@ -58,6 +63,7 @@
|
||||
{{#each fonts}}
|
||||
<tr data-table-search-row data-font-toggle-row data-font-enabled="{{#if enabled}}true{{else}}false{{/if}}">
|
||||
<td data-label="Family" class="fw-semibold">{{family}}</td>
|
||||
<td data-label="Preview" style="font-family: '{{family}}'; font-size: 1.25rem;">Aa Bb Cc 123</td>
|
||||
<td data-label="File" class="text-break">{{fileName}}</td>
|
||||
<td data-label="Format">{{format}}</td>
|
||||
<td data-label="Status">
|
||||
@@ -85,7 +91,7 @@
|
||||
{{/each}}
|
||||
{{else}}
|
||||
<tr data-table-search-empty-default>
|
||||
<td colspan="5" class="empty">No managed fonts yet.</td>
|
||||
<td colspan="6" class="empty">No managed fonts yet.</td>
|
||||
</tr>
|
||||
{{/if}}
|
||||
</tbody>
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h2>Media library</h2>
|
||||
<p>Manage reusable images and videos for slides and templates.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<link rel="stylesheet" href="/assets/vendor/cropperjs/cropper.min.css" />
|
||||
|
||||
<section class="media-gallery" data-media-gallery-offset="{{assets.length}}" data-media-gallery-has-more="{{#if hasMore}}true{{else}}false{{/if}}">
|
||||
<div class="media-gallery-toolbar">
|
||||
{{#if (hasPermission currentUser 'media-library.create')}}
|
||||
<button type="button" class="btn btn-primary btn-sm text-nowrap" data-media-library-add><i class="bi bi-plus-lg me-1" aria-hidden="true"></i>Add media</button>
|
||||
{{/if}}
|
||||
{{#if assets.length}}
|
||||
<div class="media-gallery-controls">
|
||||
<p class="media-gallery-count text-body-secondary small mb-0"><span data-media-gallery-count>{{assetTotal}}</span> item{{#unless (eq assetTotal 1)}}s{{/unless}}</p>
|
||||
<div class="media-gallery-search d-flex flex-wrap gap-2">
|
||||
<label class="visually-hidden" for="media-gallery-search-input">Search media</label>
|
||||
<div class="input-group input-group-sm">
|
||||
<span class="input-group-text"><i class="bi bi-search" aria-hidden="true"></i></span>
|
||||
<input id="media-gallery-search-input" type="search" class="form-control" placeholder="Search media" autocomplete="off" data-media-gallery-search />
|
||||
</div>
|
||||
<label class="visually-hidden" for="media-gallery-type-filter">Filter media type</label>
|
||||
<select id="media-gallery-type-filter" class="form-select form-select-sm" data-media-gallery-type-filter>
|
||||
<option value="all">All types</option>
|
||||
<option value="image">Images</option>
|
||||
<option value="video">Videos</option>
|
||||
</select>
|
||||
<label class="visually-hidden" for="media-gallery-usage-filter">Filter media usage</label>
|
||||
<select id="media-gallery-usage-filter" class="form-select form-select-sm" data-media-gallery-usage-filter>
|
||||
<option value="all">All usage</option>
|
||||
<option value="used">In use</option>
|
||||
<option value="unused">Unused</option>
|
||||
</select>
|
||||
<label class="visually-hidden" for="media-gallery-sort">Sort media</label>
|
||||
<select id="media-gallery-sort" class="form-select form-select-sm" data-media-gallery-sort>
|
||||
<option value="date-desc">Newest first</option>
|
||||
<option value="date-asc">Oldest first</option>
|
||||
<option value="name-asc">Name A-Z</option>
|
||||
<option value="name-desc">Name Z-A</option>
|
||||
<option value="size-desc">Largest first</option>
|
||||
<option value="size-asc">Smallest first</option>
|
||||
</select>
|
||||
{{#if (hasPermission currentUser 'media-library.delete')}}
|
||||
<button type="button" class="btn btn-secondary btn-sm" data-media-gallery-select-mode aria-pressed="false">Select</button>
|
||||
<button type="button" class="btn btn-danger btn-sm" data-media-gallery-delete-selected hidden disabled title="Delete selected media">Delete</button>
|
||||
{{/if}}
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<p class="media-gallery-count text-body-secondary small mb-0"><span data-media-gallery-count>{{assetTotal}}</span> item{{#unless (eq assetTotal 1)}}s{{/unless}}</p>
|
||||
{{/if}}
|
||||
</div>
|
||||
|
||||
{{#if assets.length}}
|
||||
<div class="media-gallery-scroll">
|
||||
<div class="row g-3 g-xl-4">
|
||||
{{#each assets}}
|
||||
<div class="col-12 col-sm-6 col-lg-4 col-xl-2" data-media-gallery-column data-media-id="{{id}}" data-media-type="{{media_type}}" data-media-used="{{#if inUse}}true{{else}}false{{/if}}">
|
||||
<article class="media-gallery-card" data-media-created-at="{{created_at}}" data-media-file-size="{{file_size}}">
|
||||
<button type="button" class="media-gallery-preview" data-media-gallery-preview data-media-path="{{media_path}}" data-media-type="{{media_type}}" data-media-name="{{original_name}}" aria-label="Preview {{original_name}}">
|
||||
{{#if (eq media_type 'video')}}
|
||||
<video src="{{media_path}}" muted playsinline preload="metadata"></video>
|
||||
<span class="media-gallery-play" aria-hidden="true"><i class="bi bi-play-fill"></i></span>
|
||||
{{else}}
|
||||
<img src="{{media_path}}" alt="{{original_name}}" loading="lazy" />
|
||||
{{/if}}
|
||||
<span class="media-gallery-type">{{mediaFormat}}</span>
|
||||
</button>
|
||||
<div class="media-gallery-details">
|
||||
<div class="media-gallery-header{{#if (hasPermission ../currentUser 'media-library.delete')}} media-gallery-header-selectable{{/if}}">
|
||||
<h4 class="media-gallery-name" title="{{original_name}}">{{original_name}}</h4>
|
||||
{{#if (hasPermission ../currentUser 'media-library.delete')}}
|
||||
{{#if inUse}}
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm media-gallery-action" disabled title="Media is in use"><i class="bi bi-lock" aria-hidden="true"></i><span class="visually-hidden">Media is in use</span></button>
|
||||
{{else}}
|
||||
<form method="post" action="/media-library/{{id}}/delete" data-confirm-message="Delete this media?" class="media-gallery-action">
|
||||
<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>
|
||||
</form>
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
</div>
|
||||
<div class="media-gallery-meta">{{displayFileSize}} <span aria-hidden="true">·</span> Used {{referenceCount}} time{{#unless (eq referenceCount 1)}}s{{/unless}}</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
{{/each}}
|
||||
</div>
|
||||
<div class="text-center mt-4" data-media-gallery-load-more-wrap hidden>
|
||||
<button type="button" class="btn btn-primary px-4" data-media-gallery-load-more>Load more...</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="media-gallery-empty text-body-secondary" data-media-gallery-no-results hidden>No media matches your search.</div>
|
||||
{{else}}
|
||||
<div class="media-gallery-empty text-body-secondary">No media yet.</div>
|
||||
{{/if}}
|
||||
</section>
|
||||
|
||||
{{#> modal-shell modalId="media-gallery-preview-modal" modalLabelId="media-gallery-preview-modal-label" modalDialogClass="modal-dialog-centered modal-fullscreen-md-down modal-xl"}}
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title fs-5 text-truncate" id="media-gallery-preview-modal-label">Media preview</h2>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body media-gallery-preview-modal-body" data-media-gallery-preview-body></div>
|
||||
{{/modal-shell}}
|
||||
|
||||
{{#if (hasPermission currentUser 'media-library.create')}}
|
||||
{{#> modal-shell modalId="media-library-upload-modal" modalLabelId="media-library-upload-modal-label" modalDialogClass="modal-dialog-centered modal-lg"}}
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title fs-5" id="media-library-upload-modal-label">Add media</h2>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form method="post" action="/media-library" enctype="multipart/form-data">
|
||||
<div class="modal-body">
|
||||
<label class="slide-image-region-upload-zone media-library-upload-zone" for="media-library-upload" data-media-library-upload-zone>
|
||||
<input type="file" id="media-library-upload" name="file" class="visually-hidden" accept="{{#each uploadLimits.allowedMimeTypes}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}" data-media-library-upload data-image-max-bytes="{{uploadLimits.imageMaxBytes}}" data-video-max-bytes="{{uploadLimits.videoMaxBytes}}" required />
|
||||
<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-copy">
|
||||
<strong>Drop an image or video here or click to upload</strong>
|
||||
<span>Images and videos enabled in Media Uploads settings</span>
|
||||
<span class="slide-image-region-upload-zone-limit">Images max {{uploadLimits.imageMaxLabel}}; videos max {{uploadLimits.videoMaxLabel}}</span>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</form>
|
||||
{{/modal-shell}}
|
||||
{{/if}}
|
||||
|
||||
{{#> modal-shell modalId="media-library-crop-modal" modalLabelId="media-library-crop-modal-label" modalDialogClass="modal-dialog-centered modal-xl" modalBackdropStatic=true modalKeyboardDisabled=true}}
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
<h2 class="modal-title fs-5" id="media-library-crop-modal-label">Edit image</h2>
|
||||
</div>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body d-grid gap-3">
|
||||
<div class="slide-image-cropper-frame">
|
||||
<img id="media-library-crop-image" alt="Selected image to crop" />
|
||||
<div class="slide-image-cropper-loading-overlay" aria-hidden="true">
|
||||
<div class="spinner-border text-primary slide-image-cropper-loading-spinner" role="status">
|
||||
<span class="visually-hidden">Loading image editor</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="btn-toolbar flex-wrap gap-2 slide-image-cropper-toolbar" role="toolbar" aria-label="Image editing controls">
|
||||
<div class="btn-group btn-group-sm" role="group" aria-label="Rotate">
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="rotate-left"><i class="bi bi-arrow-counterclockwise" aria-hidden="true"></i> Rotate left</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="rotate-right"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i> Rotate right</button>
|
||||
</div>
|
||||
<div class="btn-group btn-group-sm" role="group" aria-label="Flip">
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="flip-horizontal"><i class="bi bi-symmetry-vertical" aria-hidden="true"></i> Flip horizontal</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="flip-vertical"><i class="bi bi-symmetry-horizontal" aria-hidden="true"></i> Flip vertical</button>
|
||||
</div>
|
||||
<div class="btn-group btn-group-sm" role="group" aria-label="Crop ratio presets">
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="ratio" data-media-library-crop-ratio="free">Free</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="ratio" data-media-library-crop-ratio="1:1">1:1</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="ratio" data-media-library-crop-ratio="4:3">4:3</button>
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-library-crop-action="ratio" data-media-library-crop-ratio="16:9">16:9</button>
|
||||
</div>
|
||||
<button type="button" class="btn btn-outline-danger btn-sm" data-media-library-crop-action="reset"><i class="bi bi-arrow-repeat" aria-hidden="true"></i> Reset</button>
|
||||
</div>
|
||||
<p class="small text-body-secondary mb-0" id="media-library-crop-status"></p>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-end">
|
||||
<div class="btn-group" role="group" aria-label="Crop actions">
|
||||
<button type="button" class="btn btn-primary" data-media-library-crop-apply>Apply crop</button>
|
||||
<button type="button" class="btn btn-warning" data-media-library-crop-cancel>Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
{{/modal-shell}}
|
||||
|
||||
<script src="/assets/vendor/cropperjs/cropper.min.js"></script>
|
||||
<script type="module" src="/assets/js/settings/media-library.js?v={{appVersion}}"></script>
|
||||
@@ -239,6 +239,14 @@
|
||||
</a>
|
||||
</li>
|
||||
{{/if}}
|
||||
{{#if (hasPermission currentUser 'media-library.read')}}
|
||||
<li class="nav-item">
|
||||
<a class="nav-link {{#if (eq active 'media-library')}}active{{/if}}" href="/media-library">
|
||||
<i class="nav-icon bi bi-images"></i>
|
||||
<p>Media library</p>
|
||||
</a>
|
||||
</li>
|
||||
{{/if}}
|
||||
{{#if (anyPermission currentUser 'rss-feeds.read' 'schedules.read' 'api-sources.read' 'weather.read')}}
|
||||
<li class="nav-header">DATA SOURCES</li>
|
||||
{{/if}}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
{{#> modal-shell modalId="media-picker-modal" modalLabelId="media-picker-modal-label" modalDialogClass="modal-dialog-centered modal-dialog-scrollable modal-xxl"}}
|
||||
<div class="modal-header">
|
||||
<h2 class="modal-title fs-5" id="media-picker-modal-label">Choose media</h2>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="media-picker-toolbar mb-3" data-media-picker-toolbar>
|
||||
<label class="visually-hidden" for="media-picker-search">Search media</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="bi bi-search" aria-hidden="true"></i></span>
|
||||
<input id="media-picker-search" type="search" class="form-control" placeholder="Search media" autocomplete="off" data-media-picker-search />
|
||||
</div>
|
||||
<label class="visually-hidden" for="media-picker-sort">Sort media</label>
|
||||
<select id="media-picker-sort" class="form-select" data-media-picker-sort>
|
||||
<option value="date-desc">Newest first</option>
|
||||
<option value="date-asc">Oldest first</option>
|
||||
<option value="name-asc">Name A-Z</option>
|
||||
<option value="name-desc">Name Z-A</option>
|
||||
</select>
|
||||
<button type="button" class="btn btn-primary text-nowrap" data-media-picker-upload><i class="bi bi-cloud-arrow-up me-1" aria-hidden="true"></i>Upload media</button>
|
||||
</div>
|
||||
<div class="media-picker-scroll">
|
||||
<div class="row g-3" data-media-picker-grid>
|
||||
{{#if mediaAssets.length}}
|
||||
{{#each mediaAssets}}
|
||||
<div class="col-6 col-md-4 col-lg-3" data-media-picker-item data-media-type="{{media_type}}" data-media-name="{{original_name}}" data-media-created-at="{{created_at}}">
|
||||
<button type="button" class="media-picker-item w-100 text-start" data-media-picker-path="{{media_path}}" data-media-picker-type="{{media_type}}">
|
||||
<span class="media-picker-item-preview">
|
||||
{{#if (eq media_type 'video')}}
|
||||
<video src="{{media_path}}" muted playsinline preload="metadata"></video>
|
||||
{{else}}
|
||||
<img src="{{media_path}}" alt="" loading="lazy" />
|
||||
{{/if}}
|
||||
</span>
|
||||
<span class="media-picker-item-name text-truncate d-block">{{original_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>
|
||||
{{/each}}
|
||||
{{else}}
|
||||
<div class="col-12"><p class="text-body-secondary mb-0">No media has been added to the library yet.</p></div>
|
||||
{{/if}}
|
||||
</div>
|
||||
<p class="text-body-secondary mb-0" data-media-picker-no-results hidden>No matching media found.</p>
|
||||
<div class="text-center mt-3" data-media-picker-load-more-wrap hidden>
|
||||
<button type="button" class="btn btn-primary px-4" data-media-picker-load-more>Load more...</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-outline-secondary" data-media-picker-cancel>Cancel</button>
|
||||
<button type="button" class="btn btn-primary" data-media-picker-confirm>Confirm selection</button>
|
||||
</div>
|
||||
{{/modal-shell}}
|
||||
@@ -199,7 +199,7 @@
|
||||
<div class="clients-mobile-client-header"><div><h4 data-mobile-client-name>{{#if client_name}}{{client_name}}{{else}}Unknown{{/if}}</h4></div><span class="badge {{#if blackout}}text-bg-secondary{{else if paused}}text-bg-warning{{else}}text-bg-success{{/if}}">{{#if blackout}}Blackout{{else if paused}}Paused{{else}}Live{{/if}}</span></div>
|
||||
<div class="clients-mobile-client-details"><div><small>Screen group</small><strong>{{#if screen_name}}{{screen_name}}{{else}}{{screen_slug}}{{/if}}</strong></div><div><small>Now showing</small><strong>{{#if currentSlideTitle}}{{currentSlideTitle}}{{else}}No slide currently showing{{/if}}</strong></div></div>
|
||||
{{#if (hasPermission ../currentUser 'clients.allow')}}
|
||||
<div class="clients-mobile-client-actions"><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form" data-async-command><input type="hidden" name="command" value="reload" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-danger" aria-label="Reload client" title="Reload client"><i class="bi bi-arrow-repeat" aria-hidden="true"></i></button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form" data-async-command><input type="hidden" name="command" value="previous" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-warning" aria-label="Previous slide" title="Previous slide"><i class="bi bi-skip-backward-fill" aria-hidden="true"></i></button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form" data-async-command><input type="hidden" name="command" value="next" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-warning" aria-label="Next slide" title="Next slide"><i class="bi bi-skip-forward-fill" aria-hidden="true"></i></button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form wide" data-async-command><input type="hidden" name="command" value="pause" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-info w-100" aria-label="Pause client" title="Pause client"><i class="bi {{#if paused}}bi-play-fill{{else}}bi-pause-fill{{/if}} me-1" aria-hidden="true"></i>{{#if paused}}Resume{{else}}Pause{{/if}}</button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form wide" data-async-command><input type="hidden" name="command" value="blackout" /><input type="hidden" name="blackout" value="{{#if blackout}}false{{else}}true{{/if}}" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm {{#if blackout}}btn-success{{else}}btn-secondary{{/if}} w-100" aria-label="{{#if blackout}}Restore client{{else}}Blackout client{{/if}}" title="{{#if blackout}}Restore client{{else}}Blackout client{{/if}}"><i class="bi {{#if blackout}}bi-eye{{else}}bi-eye-slash{{/if}} me-1" aria-hidden="true"></i>{{#if blackout}}Restore{{else}}Blackout{{/if}}</button></form></div>
|
||||
<div class="clients-mobile-client-actions"><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form" data-confirm-message="Reloading will restart the player page. Continue?" data-async-command><input type="hidden" name="command" value="reload" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-danger" aria-label="Reload client" title="Reload client"><i class="bi bi-arrow-repeat" aria-hidden="true"></i></button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form" data-async-command><input type="hidden" name="command" value="previous" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-warning" aria-label="Previous slide" title="Previous slide"><i class="bi bi-skip-backward-fill" aria-hidden="true"></i></button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form" data-async-command><input type="hidden" name="command" value="next" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-warning" aria-label="Next slide" title="Next slide"><i class="bi bi-skip-forward-fill" aria-hidden="true"></i></button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form wide" data-async-command><input type="hidden" name="command" value="pause" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm btn-info w-100" aria-label="Pause client" title="Pause client"><i class="bi {{#if paused}}bi-play-fill{{else}}bi-pause-fill{{/if}} me-1" aria-hidden="true"></i>{{#if paused}}Resume{{else}}Pause{{/if}}</button></form><form method="post" action="/clients/{{screen_slug}}/commands" class="inline-form wide" data-async-command><input type="hidden" name="command" value="blackout" /><input type="hidden" name="blackout" value="{{#if blackout}}false{{else}}true{{/if}}" /><input type="hidden" name="connectionId" value="{{id}}" /><input type="hidden" name="playerBaseUrl" value="{{player_url}}" /><button type="submit" class="btn btn-sm {{#if blackout}}btn-success{{else}}btn-secondary{{/if}} w-100" aria-label="{{#if blackout}}Restore client{{else}}Blackout client{{/if}}" title="{{#if blackout}}Restore client{{else}}Blackout client{{/if}}"><i class="bi {{#if blackout}}bi-eye{{else}}bi-eye-slash{{/if}} me-1" aria-hidden="true"></i>{{#if blackout}}Restore{{else}}Blackout{{/if}}</button></form></div>
|
||||
{{/if}}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -118,6 +118,8 @@
|
||||
</div>
|
||||
{{/modal-shell}}
|
||||
|
||||
{{> media-picker-modal mediaAssets=slideEditorData.mediaAssets}}
|
||||
|
||||
{{#if isEdit}}
|
||||
<form id="delete-slide-form" method="post" action="/slides/{{slide.id}}/delete" data-confirm-message="Delete this slide?"></form>
|
||||
{{/if}}
|
||||
@@ -132,4 +134,5 @@
|
||||
{{/each}}
|
||||
<script type="module" src="/assets/js/slides/slide-form.js?v={{assetVersion}}"></script>
|
||||
<script type="module" src="/assets/js/slides/slide-image-cropper.js?v={{assetVersion}}"></script>
|
||||
<script type="module" src="/assets/js/media-picker.js?v={{appVersion}}"></script>
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<input type="hidden" name="canvas_width" id="canvas-width" value="{{template.canvas_size_width}}" />
|
||||
<input type="hidden" name="canvas_height" id="canvas-height" value="{{template.canvas_size_height}}" />
|
||||
<input type="hidden" id="canvas-size-summary" />
|
||||
<input type="hidden" name="existing_background_image_path" value="{{template.background_image_path}}" />
|
||||
<input type="hidden" name="existing_background_image_path" id="existing-background-image-path" value="{{template.background_image_path}}" />
|
||||
<input type="hidden" name="regions_json" id="regions-json" value="" />
|
||||
<textarea id="template-region-usage" hidden>{{json template.region_usage}}</textarea>
|
||||
|
||||
@@ -98,22 +98,27 @@
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-12 col-md-6">
|
||||
<label for="background-image" class="form-label">Background image</label>
|
||||
<div class="template-background-row d-flex gap-2">
|
||||
<input type="file" name="background_image" id="background-image" class="form-control" accept="image/*" />
|
||||
<button type="button" class="btn btn-outline-secondary" id="remove-background-image">Remove</button>
|
||||
<div class="col-12 col-md-9">
|
||||
<span class="form-label d-block">Background image</span>
|
||||
<div class="row g-3">
|
||||
<div class="col-12 col-md-4">
|
||||
<input type="file" name="background_image" id="background-image" class="d-none" accept="image/*" />
|
||||
<button type="button" class="btn btn-outline-secondary w-100" data-media-picker data-media-picker-type="image" data-media-picker-hidden="existing-background-image-path"><i class="bi bi-images me-1" aria-hidden="true"></i>Choose</button>
|
||||
</div>
|
||||
<div class="col-12 col-md-4">
|
||||
<button type="button" class="btn btn-outline-secondary w-100" id="remove-background-image">Remove</button>
|
||||
</div>
|
||||
<div class="col-12 col-md-4">
|
||||
<button type="button" class="btn btn-outline-secondary w-100" data-bs-toggle="modal" data-bs-target="#background-advanced-modal"><i class="bi bi-sliders me-1" aria-hidden="true"></i>Advanced background</button>
|
||||
</div>
|
||||
</div>
|
||||
<input type="checkbox" name="remove_background_image" id="remove-background-image-flag" value="1" hidden />
|
||||
</div>
|
||||
<div class="col-12 col-md-6">
|
||||
<div class="col-12 col-md-3">
|
||||
<label for="background-color" class="form-label">Background colour</label>
|
||||
<input type="color" name="background_color" id="background-color" class="form-control form-control-color w-100" value="{{#if template.background_color}}{{template.background_color}}{{else}}#111111{{/if}}" title="Choose a background colour" />
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<input type="hidden" name="background_gradient" id="background-gradient" value="{{template.background_gradient}}" />
|
||||
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#background-advanced-modal"><i class="bi bi-sliders me-1" aria-hidden="true"></i>Advanced background</button>
|
||||
</div>
|
||||
<input type="hidden" name="background_gradient" id="background-gradient" value="{{template.background_gradient}}" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -224,4 +229,7 @@
|
||||
|
||||
{{> signage/templates/animation-advanced-modal}}
|
||||
|
||||
<textarea id="template-editor-data" hidden>{{json template.regions}}</textarea>
|
||||
{{> media-picker-modal mediaAssets=mediaAssets}}
|
||||
|
||||
<textarea id="template-editor-data" hidden>{{json template.regions}}</textarea>
|
||||
<script type="module" src="/assets/js/media-picker.js?v={{appVersion}}"></script>
|
||||
+25
-13
@@ -1,6 +1,8 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
require('../src/common');
|
||||
|
||||
@@ -172,7 +174,11 @@ test('canvas size update returns a warning when an in-use canvas changes dimensi
|
||||
assert.equal(queries.length, 2);
|
||||
});
|
||||
|
||||
test('slide upload cleanup route removes unused uploads', async () => {
|
||||
test('slide upload cleanup route removes pending media assets', async () => {
|
||||
const uploadRoot = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'pulse-slide-upload-cleanup-'));
|
||||
const uploadDir = path.join(uploadRoot, 'media', 'uploads');
|
||||
await fs.promises.mkdir(uploadDir, { recursive: true });
|
||||
await fs.promises.writeFile(path.join(uploadDir, 'test-file.png'), Buffer.from('temporary upload'));
|
||||
const handlers = {};
|
||||
const app = {
|
||||
get(path, ...routeHandlers) {
|
||||
@@ -183,12 +189,16 @@ test('slide upload cleanup route removes unused uploads', async () => {
|
||||
}
|
||||
};
|
||||
|
||||
let cleanupCall = null;
|
||||
|
||||
const deps = {
|
||||
pool: {
|
||||
async query() {
|
||||
return [[]];
|
||||
async query(sql) {
|
||||
if (String(sql).includes('is_published = 0')) {
|
||||
return [[{ id: 1 }]];
|
||||
}
|
||||
if (String(sql).includes('DELETE FROM c_media_assets')) {
|
||||
return [{ affectedRows: 1 }];
|
||||
}
|
||||
return [[{ ref_count: 0 }]];
|
||||
}
|
||||
},
|
||||
common: {
|
||||
@@ -239,9 +249,7 @@ test('slide upload cleanup route removes unused uploads', async () => {
|
||||
collectUploadReferencesFromSlide: () => [],
|
||||
collectUploadReferencesFromTemplate: () => [],
|
||||
collectUploadReferencesFromPayload: () => [],
|
||||
removeUnusedUploadFiles: async (pool, uploadDir, uploadPaths) => {
|
||||
cleanupCall = { pool, uploadDir, uploadPaths };
|
||||
},
|
||||
removeUnusedUploadFiles: async () => {},
|
||||
syncPlaylistUploadsOnChange: async () => {},
|
||||
getAuditUserId: () => 1,
|
||||
redirectAfterSave: () => {},
|
||||
@@ -257,7 +265,7 @@ test('slide upload cleanup route removes unused uploads', async () => {
|
||||
};
|
||||
},
|
||||
hasAnyPermission: () => true,
|
||||
uploadDir: 'e:\\Projects Git\\pulse-signage\\media\\uploads'
|
||||
uploadDir
|
||||
};
|
||||
|
||||
registerContentRoutes(app, deps);
|
||||
@@ -286,11 +294,15 @@ test('slide upload cleanup route removes unused uploads', async () => {
|
||||
}
|
||||
};
|
||||
|
||||
await routeHandlers[1](req, res, () => {});
|
||||
try {
|
||||
await routeHandlers[1](req, res, () => {});
|
||||
|
||||
assert.equal(res.statusCode, 204);
|
||||
assert.equal(cleanupCall.uploadDir, 'e:\\Projects Git\\pulse-signage\\media\\uploads');
|
||||
assert.deepEqual(cleanupCall.uploadPaths, ['/media/uploads/test-file.png']);
|
||||
assert.equal(res.statusCode, 204);
|
||||
assert.equal(fs.existsSync(path.join(uploadDir, 'test-file.png')), false);
|
||||
assert.equal(res.statusCode, 204);
|
||||
} finally {
|
||||
await fs.promises.rm(uploadRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('wysiwyg image uploads are capped below the dedicated image region limit', async () => {
|
||||
|
||||
@@ -108,4 +108,9 @@ test('clients page renders action cells for clients with permission', () => {
|
||||
assert.match(html, /data-label="Actions"/);
|
||||
assert.match(html, /Pause client/);
|
||||
assert.match(html, /Blackout client/);
|
||||
});
|
||||
|
||||
assert.match(html, /data-confirm-message="Reloading will restart the player page\. Continue\?"/);
|
||||
const mobileClientsMarkup = html.slice(html.indexOf('<section class="clients-mobile-clients"'));
|
||||
assert.match(mobileClientsMarkup, /name="command" value="reload"/);
|
||||
assert.match(mobileClientsMarkup, /data-confirm-message="Reloading will restart the player page\. Continue\?"/);
|
||||
});
|
||||
|
||||
@@ -210,7 +210,7 @@ test('fonts page renders the upload card above the table card', () => {
|
||||
nextUrl: '?page=2',
|
||||
pages: [{ number: 1, active: true, url: '' }]
|
||||
},
|
||||
stylesheetHref: ''
|
||||
stylesheetHref: '/media/fonts/fonts.css?v=1'
|
||||
}, '', { id: 1 });
|
||||
|
||||
assert.ok(html.indexOf('Upload font') < html.indexOf('Managed fonts'));
|
||||
@@ -219,6 +219,9 @@ test('fonts page renders the upload card above the table card', () => {
|
||||
assert.match(html, /data-async-command/);
|
||||
assert.match(html, /data-font-toggle-row/);
|
||||
assert.match(html, /data-font-status-badge/);
|
||||
assert.match(html, /<link rel="stylesheet" href="\/media\/fonts\/fonts\.css\?v=1" \/>/);
|
||||
assert.match(html, /<th>Preview<\/th>/);
|
||||
assert.match(html, /font-family: 'Alpha Sans';/);
|
||||
assert.match(html, /data-table-sort-key="family"/);
|
||||
assert.match(html, /data-table-sort-key="file"/);
|
||||
assert.match(html, /data-table-sort-key="format"/);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const {
|
||||
normalizeMediaPath,
|
||||
registerMediaAssets,
|
||||
syncMediaAssetsFromDirectory,
|
||||
countMediaAssetReferences
|
||||
} = require('../src/web/lib/media/library');
|
||||
|
||||
test('media library normalizes only media URLs', () => {
|
||||
assert.equal(normalizeMediaPath('/media/uploads/photo.png'), '/media/uploads/photo.png');
|
||||
assert.equal(normalizeMediaPath(' /media/video.mp4 '), '/media/video.mp4');
|
||||
assert.equal(normalizeMediaPath('/assets/photo.png'), null);
|
||||
});
|
||||
|
||||
test('media library registers uploaded files with their metadata', async () => {
|
||||
const queries = [];
|
||||
const pool = {
|
||||
async query(sql, params) {
|
||||
queries.push({ sql, params });
|
||||
return [{ affectedRows: 1 }];
|
||||
}
|
||||
};
|
||||
const registered = await registerMediaAssets(pool, [{
|
||||
filename: 'upload.png',
|
||||
originalname: 'Photo.png',
|
||||
mimetype: 'image/png',
|
||||
size: 42
|
||||
}], file => '/media/uploads/' + file.filename, () => 'image', 7);
|
||||
|
||||
assert.deepEqual(registered, ['/media/uploads/upload.png']);
|
||||
assert.match(queries[0].sql, /INSERT INTO c_media_assets/);
|
||||
assert.deepEqual(queries[0].params, [
|
||||
'/media/uploads/upload.png',
|
||||
'Photo.png',
|
||||
'image',
|
||||
'image/png',
|
||||
42,
|
||||
1,
|
||||
7,
|
||||
7
|
||||
]);
|
||||
});
|
||||
|
||||
test('media library backfills existing image and video uploads', async () => {
|
||||
const uploadDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'pulse-media-library-'));
|
||||
await fs.promises.writeFile(path.join(uploadDir, 'legacy.png'), Buffer.from('image'));
|
||||
await fs.promises.writeFile(path.join(uploadDir, 'legacy.mp4'), Buffer.from('video'));
|
||||
await fs.promises.writeFile(path.join(uploadDir, 'ignore.txt'), Buffer.from('other'));
|
||||
const queries = [];
|
||||
const pool = {
|
||||
async query(sql, params) {
|
||||
queries.push({ sql, params });
|
||||
return [{ affectedRows: 1 }];
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
assert.equal(await syncMediaAssetsFromDirectory(pool, uploadDir), 2);
|
||||
assert.deepEqual(queries.map(query => query.params[0]).sort(), [
|
||||
'/media/uploads/legacy.mp4',
|
||||
'/media/uploads/legacy.png'
|
||||
]);
|
||||
assert.match(queries[0].sql, /original_name = original_name/);
|
||||
assert.match(queries[0].sql, /is_published = is_published/);
|
||||
} finally {
|
||||
await fs.promises.rm(uploadDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('media library counts slide and template references', async () => {
|
||||
const queries = [];
|
||||
const pool = {
|
||||
async query(sql, params) {
|
||||
queries.push({ sql, params });
|
||||
if (sql.includes('FROM c_slides')) {
|
||||
return [[{ ref_count: 2 }]];
|
||||
}
|
||||
return [[{ ref_count: 1 }]];
|
||||
}
|
||||
};
|
||||
|
||||
assert.equal(await countMediaAssetReferences(pool, '/media/uploads/shared.png'), 3);
|
||||
assert.equal(queries.length, 2);
|
||||
assert.equal(queries[0].params[0], '/media/uploads/shared.png');
|
||||
assert.equal(queries[1].params[0], '/media/uploads/shared.png');
|
||||
assert.match(queries[0].sql, /LOCATE/);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const { registerPlayerControlSyncTask } = require('../src/web/lib/background-tasks/tasks-scheduled/player-control-sync');
|
||||
|
||||
test('player control sync sends minimized authorization data to remote players only', async () => {
|
||||
let task = null;
|
||||
const forwarded = [];
|
||||
registerPlayerControlSyncTask({
|
||||
pool: {
|
||||
async query() {
|
||||
return [[{
|
||||
username: 'operator',
|
||||
password_hash: 'hash',
|
||||
password_salt: 'salt'
|
||||
}]];
|
||||
}
|
||||
},
|
||||
common: {
|
||||
async fetchPlayerRegistrations() {
|
||||
return [
|
||||
{ identifier: 'local', internal_base_url: 'http://player:8081' },
|
||||
{ identifier: 'remote', internal_base_url: 'http://remote-player:8081' }
|
||||
];
|
||||
}
|
||||
},
|
||||
backgroundTaskQueue: {
|
||||
registerRecurringTask(value) {
|
||||
task = value;
|
||||
}
|
||||
},
|
||||
localPlayerInternalUrl: 'http://player:8081',
|
||||
forwardPlayerCommandToDevice: async function (deviceId, payload) {
|
||||
forwarded.push({ deviceId, payload });
|
||||
}
|
||||
});
|
||||
|
||||
assert.equal(task.intervalMs, 15 * 60 * 1000);
|
||||
await task.run();
|
||||
assert.deepEqual(forwarded, [{
|
||||
deviceId: 'remote',
|
||||
payload: {
|
||||
command: 'sync-local-control',
|
||||
users: [{
|
||||
username_hash: crypto.createHash('sha256').update('operator').digest('hex'),
|
||||
password_hash: 'hash',
|
||||
password_salt: 'salt'
|
||||
}]
|
||||
}
|
||||
}]);
|
||||
});
|
||||
@@ -0,0 +1,204 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { WebSocket } = require('ws');
|
||||
|
||||
require('../src/common');
|
||||
|
||||
const { hashPassword } = require('../src/auth');
|
||||
const { createLocalControlService } = require('../src/player/local-control');
|
||||
|
||||
async function createTestService(options) {
|
||||
const temporaryDirectory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'pulse-local-control-'));
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
const server = http.createServer(app);
|
||||
const service = createLocalControlService(Object.assign({
|
||||
app: app,
|
||||
server: server,
|
||||
playerRuntime: {
|
||||
snapshotSlugs() { return ['screen-a']; },
|
||||
snapshotConnections() { return [{ id: 'client-a', clientName: 'Lobby', currentSlideTitle: 'Welcome' }]; },
|
||||
async sendCommandToConnection() { return 1; }
|
||||
},
|
||||
playerIdentifier: 'test-player',
|
||||
cachePath: path.join(temporaryDirectory, 'users.json')
|
||||
}, options || {}));
|
||||
return { app, server, service, temporaryDirectory };
|
||||
}
|
||||
|
||||
test('local control authenticates only cached eligible users and scopes commands to local runtime', async () => {
|
||||
const { app, service, temporaryDirectory } = await createTestService();
|
||||
const password = hashPassword('CorrectHorseBatteryStaple!');
|
||||
await service.saveUsers([{
|
||||
id: 7,
|
||||
name: 'Operator',
|
||||
username: 'operator',
|
||||
email: 'operator@example.com',
|
||||
password_hash: password.hash,
|
||||
password_salt: password.salt,
|
||||
password_iterations: password.iterations
|
||||
}]);
|
||||
await service.loadCache();
|
||||
|
||||
const cachedUsers = JSON.parse(await fs.promises.readFile(path.join(temporaryDirectory, 'users.json'), 'utf8')).users;
|
||||
assert.equal(cachedUsers[0].id, undefined);
|
||||
assert.equal(cachedUsers[0].name, undefined);
|
||||
assert.equal(cachedUsers[0].email, undefined);
|
||||
assert.equal(cachedUsers[0].username, undefined);
|
||||
assert.equal(cachedUsers[0].password_iterations, undefined);
|
||||
const server = app.listen(0);
|
||||
try {
|
||||
const address = server.address();
|
||||
const login = await fetch(`http://127.0.0.1:${address.port}/local-control/api/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'operator', password: 'CorrectHorseBatteryStaple!' })
|
||||
});
|
||||
assert.equal(login.status, 200);
|
||||
const setCookie = login.headers.get('set-cookie');
|
||||
assert.match(setCookie, /^pulse_local_control_test-player_session=/);
|
||||
const cookie = setCookie.split(';')[0];
|
||||
|
||||
const state = await fetch(`http://127.0.0.1:${address.port}/local-control/api/state`, {
|
||||
headers: { cookie: cookie }
|
||||
});
|
||||
assert.equal(state.status, 200);
|
||||
const stateBody = await state.json();
|
||||
assert.equal(stateBody.screens[0].name, 'screen-a');
|
||||
assert.deepEqual(stateBody.screens[0].connections[0].clientName, 'Lobby');
|
||||
assert.equal(stateBody.screens[0].connections[0].currentSlideTitle, 'Welcome');
|
||||
|
||||
const page = await fetch(`http://127.0.0.1:${address.port}/local-control`);
|
||||
const pageBody = await page.text();
|
||||
assert.ok(pageBody.indexOf('<th>Client</th><th>Screen</th><th>Current Slide</th><th>Actions</th>') !== -1);
|
||||
assert.ok(pageBody.indexOf('@media (max-width: 600px)') !== -1);
|
||||
assert.equal(pageBody.indexOf('<th>Status</th>'), -1);
|
||||
|
||||
const command = await fetch(`http://127.0.0.1:${address.port}/local-control/api/commands`, {
|
||||
method: 'POST',
|
||||
headers: { cookie: cookie, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ slug: 'screen-a', connectionId: 'client-a', command: 'reload' })
|
||||
});
|
||||
assert.equal(command.status, 200);
|
||||
|
||||
const invalidLogin = await fetch(`http://127.0.0.1:${address.port}/local-control/api/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'other-user', password: 'CorrectHorseBatteryStaple!' })
|
||||
});
|
||||
assert.equal(invalidLogin.status, 401);
|
||||
|
||||
const emailLogin = await fetch(`http://127.0.0.1:${address.port}/local-control/api/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'operator@example.com', password: 'CorrectHorseBatteryStaple!' })
|
||||
});
|
||||
assert.equal(emailLogin.status, 401);
|
||||
} finally {
|
||||
await new Promise(function (resolve) { server.close(resolve); });
|
||||
await fs.promises.rm(temporaryDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('local control refuses login when the cached authorization is stale', async () => {
|
||||
const { app, service, temporaryDirectory } = await createTestService({ cacheMaxAgeMs: 1 });
|
||||
const password = hashPassword('CorrectHorseBatteryStaple!');
|
||||
await service.saveUsers([{
|
||||
id: 7,
|
||||
name: 'Operator',
|
||||
username: 'operator',
|
||||
password_hash: password.hash,
|
||||
password_salt: password.salt,
|
||||
password_iterations: password.iterations
|
||||
}]);
|
||||
await service.loadCache();
|
||||
await new Promise(function (resolve) { setTimeout(resolve, 5); });
|
||||
|
||||
const server = app.listen(0);
|
||||
try {
|
||||
const address = server.address();
|
||||
const response = await fetch(`http://127.0.0.1:${address.port}/local-control/api/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'operator', password: 'CorrectHorseBatteryStaple!' })
|
||||
});
|
||||
assert.equal(response.status, 503);
|
||||
} finally {
|
||||
await new Promise(function (resolve) { server.close(resolve); });
|
||||
await fs.promises.rm(temporaryDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('local control throttles repeated failed logins', async () => {
|
||||
const { app, service, temporaryDirectory } = await createTestService({ loginRateLimitMaxAttempts: 2, loginRateLimitWindowMs: 60 * 1000 });
|
||||
const password = hashPassword('CorrectHorseBatteryStaple!');
|
||||
await service.saveUsers([{
|
||||
username: 'operator',
|
||||
password_hash: password.hash,
|
||||
password_salt: password.salt
|
||||
}]);
|
||||
await service.loadCache();
|
||||
|
||||
const server = app.listen(0);
|
||||
try {
|
||||
const address = server.address();
|
||||
const login = function (passwordValue) {
|
||||
return fetch(`http://127.0.0.1:${address.port}/local-control/api/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'operator', password: passwordValue })
|
||||
});
|
||||
};
|
||||
assert.equal((await login('wrong-password')).status, 401);
|
||||
assert.equal((await login('wrong-password')).status, 401);
|
||||
const blocked = await login('CorrectHorseBatteryStaple!');
|
||||
assert.equal(blocked.status, 429);
|
||||
assert.equal(blocked.headers.get('retry-after') !== null, true);
|
||||
} finally {
|
||||
await new Promise(function (resolve) { server.close(resolve); });
|
||||
await fs.promises.rm(temporaryDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('local control closes live sockets when authorization is revoked', async () => {
|
||||
const { server, service, temporaryDirectory } = await createTestService();
|
||||
const password = hashPassword('CorrectHorseBatteryStaple!');
|
||||
await service.saveUsers([{
|
||||
username: 'operator',
|
||||
password_hash: password.hash,
|
||||
password_salt: password.salt
|
||||
}]);
|
||||
await service.loadCache();
|
||||
|
||||
await new Promise(function (resolve) { server.listen(0, resolve); });
|
||||
let socket;
|
||||
try {
|
||||
const address = server.address();
|
||||
const login = await fetch(`http://127.0.0.1:${address.port}/local-control/api/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'operator', password: 'CorrectHorseBatteryStaple!' })
|
||||
});
|
||||
const cookie = login.headers.get('set-cookie').split(';')[0];
|
||||
socket = new WebSocket(`ws://127.0.0.1:${address.port}/local-control/ws`, { headers: { Cookie: cookie } });
|
||||
await new Promise(function (resolve, reject) {
|
||||
socket.once('open', resolve);
|
||||
socket.once('error', reject);
|
||||
});
|
||||
const closed = new Promise(function (resolve) { socket.once('close', resolve); });
|
||||
await service.saveUsers([]);
|
||||
await Promise.race([
|
||||
closed,
|
||||
new Promise(function (_resolve, reject) { setTimeout(function () { reject(new Error('WebSocket was not closed after authorization revocation.')); }, 1000); })
|
||||
]);
|
||||
} finally {
|
||||
if (socket && socket.readyState !== WebSocket.CLOSED) { socket.close(); }
|
||||
await new Promise(function (resolve) { server.close(resolve); });
|
||||
await fs.promises.rm(temporaryDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -28,7 +28,7 @@ test('pending migrations are empty when the schema already matches the app versi
|
||||
match(sql) {
|
||||
return sql.includes('FROM information_schema.COLUMNS') && sql.includes('TABLE_NAME = ?') && sql.includes('COLUMN_NAME = ?');
|
||||
},
|
||||
result: [[{ column_count: 0 }]]
|
||||
result: [[{ column_count: 1 }]]
|
||||
},
|
||||
{
|
||||
match(_sql, params) {
|
||||
@@ -44,7 +44,7 @@ test('pending migrations are empty when the schema already matches the app versi
|
||||
}
|
||||
]);
|
||||
|
||||
const pendingMigrations = await getPendingMigrations(pool, { currentVersion: '2.11.1' });
|
||||
const pendingMigrations = await getPendingMigrations(pool, { currentVersion: '2.13.1' });
|
||||
|
||||
assert.equal(pendingMigrations.length, 0);
|
||||
});
|
||||
|
||||
@@ -9,6 +9,29 @@ require('../src/common');
|
||||
|
||||
const { createUploadSyncService } = require('../src/web/lib/media');
|
||||
|
||||
test('upload reference collection includes WYSIWYG images across slide regions', () => {
|
||||
const uploadSyncService = createUploadSyncService({
|
||||
common: { parseJsonSafe: value => value ? JSON.parse(value) : null },
|
||||
playerSnapshotCache: new Map(),
|
||||
notifyPlayerScreens: async () => {}
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
Array.from(uploadSyncService.collectUploadReferencesFromPayload({
|
||||
contentJson: JSON.stringify({
|
||||
clock: { value: '<p><img src="http://localhost:8080/media/uploads/clock-image.png"></p>' },
|
||||
html: { value: '<p><img src="/media/uploads/html-image.png"></p>' },
|
||||
rss: { value: '<p><img src="/media/uploads/rss-image.png"></p>' }
|
||||
})
|
||||
})).sort(),
|
||||
[
|
||||
'/media/uploads/clock-image.png',
|
||||
'/media/uploads/html-image.png',
|
||||
'/media/uploads/rss-image.png'
|
||||
].sort()
|
||||
);
|
||||
});
|
||||
|
||||
test('multipart uploads accept large text fields used by slide and template forms', async () => {
|
||||
const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-signage-upload-'));
|
||||
const uploadSyncService = createUploadSyncService({
|
||||
@@ -277,7 +300,7 @@ test('stale player registrations stop media sync retries and warnings', async ()
|
||||
}
|
||||
});
|
||||
|
||||
test('slide update sync removes uploads that were removed from the slide on the player', async () => {
|
||||
test('slide update sync removes uploads only after the web-managed file is gone', async () => {
|
||||
const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-signage-upload-sync-slide-remove-'));
|
||||
fs.mkdirSync(path.join(uploadDir, 'uploads'), { recursive: true });
|
||||
fs.writeFileSync(path.join(uploadDir, 'uploads', 'keep.bin'), Buffer.from('keep'));
|
||||
@@ -332,7 +355,7 @@ test('slide update sync removes uploads that were removed from the slide on the
|
||||
return [[
|
||||
{
|
||||
identifier: 'player-one',
|
||||
internal_base_url: 'http://player-one:8081',
|
||||
internal_base_url: 'http://player:8081',
|
||||
last_seen_at: liveLastSeenAt
|
||||
}
|
||||
]];
|
||||
@@ -358,10 +381,23 @@ test('slide update sync removes uploads that were removed from the slide on the
|
||||
});
|
||||
|
||||
assert.equal(fs.existsSync(path.join(uploadDir, 'uploads', 'keep.bin')), true);
|
||||
assert.equal(fs.existsSync(path.join(uploadDir, 'uploads', 'remove.bin')), false);
|
||||
assert.equal(fs.existsSync(path.join(uploadDir, 'uploads', 'remove.bin')), true);
|
||||
assert.equal(fetchCalls.filter(function (call) {
|
||||
return call.method === 'PUT';
|
||||
}).length, 1);
|
||||
assert.equal(fetchCalls.filter(function (call) {
|
||||
return call.method === 'DELETE';
|
||||
}).length, 0);
|
||||
|
||||
fs.unlinkSync(path.join(uploadDir, 'uploads', 'remove.bin'));
|
||||
await uploadSyncService.syncPlaylistUploadsOnChange({
|
||||
key: 'slide:update:124',
|
||||
pool: {},
|
||||
localUploadDir: uploadDir,
|
||||
previousUploadRefs: ['/media/uploads/remove.bin'],
|
||||
nextUploadRefs: []
|
||||
});
|
||||
|
||||
assert.equal(fetchCalls.filter(function (call) {
|
||||
return call.method === 'DELETE';
|
||||
}).length, 1);
|
||||
@@ -498,4 +534,37 @@ test('remote media sync uses the bridge device route', async () => {
|
||||
global.fetch = originalFetch;
|
||||
fs.rmSync(uploadDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('remote media deletion uses the bridge device route', async () => {
|
||||
const uploadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-signage-upload-delete-bridge-'));
|
||||
const activeLastSeenAt = new Date(Date.now() - 10_000).toISOString();
|
||||
const fetchCalls = [];
|
||||
const originalFetch = global.fetch;
|
||||
global.fetch = async function (url, init) {
|
||||
fetchCalls.push({ url, init });
|
||||
return { ok: true, status: 200, statusText: 'OK', headers: { get() { return null; } }, async text() { return ''; } };
|
||||
};
|
||||
|
||||
const uploadSyncService = createUploadSyncService({
|
||||
common: {},
|
||||
bridgeInternalBaseUrl: 'http://player-bridge:8090',
|
||||
pool: {
|
||||
async query() {
|
||||
return [[{ identifier: 'player-remote', internal_base_url: 'https://remote-player.example', last_seen_at: activeLastSeenAt }]];
|
||||
}
|
||||
},
|
||||
playerSnapshotCache: new Map(),
|
||||
notifyPlayerScreens: async () => {}
|
||||
});
|
||||
|
||||
try {
|
||||
assert.equal(await uploadSyncService.removeUploadFileFromPlayer('/media/uploads/sample.bin', uploadDir), true);
|
||||
assert.equal(fetchCalls[0].url, 'http://player-bridge:8090/api/media/uploads%2Fsample.bin');
|
||||
assert.equal(fetchCalls[0].init.method, 'DELETE');
|
||||
assert.equal(fetchCalls[0].init.headers['x-pulse-player-device-id'], 'player-remote');
|
||||
} finally {
|
||||
global.fetch = originalFetch;
|
||||
fs.rmSync(uploadDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user