Compare commits
14
Commits
09808a2136
..
v1.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38dc02aea5 | ||
|
|
4d2f7df217 | ||
|
|
df98b2c1f8 | ||
|
|
b85fbc2d90 | ||
|
|
f5f202794f | ||
|
|
a199fe452c | ||
|
|
29cd6dfaeb | ||
|
|
9180da16be | ||
|
|
d3fbaef417 | ||
|
|
c02469c6d0 | ||
|
|
1b7b836b3e | ||
|
|
609a16f468 | ||
|
|
c967b062a2 | ||
|
|
a8e0dcaf37 |
+26
-19
@@ -15,44 +15,51 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: linux/amd64
|
||||
container:
|
||||
image: gitea.tourolle.paris/dtourolle/jellylms-builder:latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
path: build-${{ github.run_id }}
|
||||
|
||||
- name: Verify .NET installation
|
||||
run: dotnet --version
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.nuget/packages
|
||||
key: nuget-${{ hashFiles('**/Jellyfin.Plugin.JellyLMS.csproj') }}
|
||||
restore-keys: nuget-
|
||||
|
||||
- name: Restore dependencies
|
||||
working-directory: build-${{ github.run_id }}
|
||||
run: dotnet restore Jellyfin.Plugin.JellyLMS.sln
|
||||
|
||||
- name: Build solution
|
||||
run: dotnet build Jellyfin.Plugin.JellyLMS.sln --configuration Release --no-restore --no-self-contained
|
||||
|
||||
- name: Install JPRM
|
||||
run: |
|
||||
python3 -m venv /tmp/jprm-venv
|
||||
/tmp/jprm-venv/bin/pip install jprm
|
||||
working-directory: build-${{ github.run_id }}
|
||||
run: dotnet build Jellyfin.Plugin.JellyLMS.sln --configuration Release --no-restore --no-self-contained /m:1
|
||||
|
||||
- name: Build Jellyfin Plugin
|
||||
id: jprm
|
||||
working-directory: build-${{ github.run_id }}
|
||||
run: |
|
||||
# Create artifacts directory for JPRM output
|
||||
mkdir -p artifacts
|
||||
|
||||
# Build plugin using JPRM
|
||||
/tmp/jprm-venv/bin/jprm --verbosity=debug plugin build .
|
||||
|
||||
# Find the generated zip file
|
||||
ARTIFACT=$(find . -name "*.zip" -type f -print -quit)
|
||||
echo "artifact=${ARTIFACT}" >> $GITHUB_OUTPUT
|
||||
echo "Found artifact: ${ARTIFACT}"
|
||||
jprm --verbosity=debug plugin build .
|
||||
ARTIFACT=$(find . -name "*.zip" -type f -print -quit | sed 's|^\./||')
|
||||
LATEST="artifacts/jellylms_latest.zip"
|
||||
cp "${ARTIFACT}" "${LATEST}"
|
||||
echo "artifact=${LATEST}" >> $GITHUB_OUTPUT
|
||||
echo "Found artifact: ${ARTIFACT} -> ${LATEST}"
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: jellylms-plugin
|
||||
path: ${{ steps.jprm.outputs.artifact }}
|
||||
path: build-${{ github.run_id }}/${{ steps.jprm.outputs.artifact }}
|
||||
retention-days: 30
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: rm -rf build-${{ github.run_id }}
|
||||
|
||||
@@ -13,19 +13,15 @@ on:
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: linux/amd64
|
||||
container:
|
||||
image: gitea.tourolle.paris/dtourolle/jellylms-builder:latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET 9
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '9.0.x'
|
||||
|
||||
- name: Verify .NET installation
|
||||
run: dotnet --version
|
||||
path: release-${{ github.run_id }}
|
||||
|
||||
- name: Get version
|
||||
id: get_version
|
||||
@@ -40,39 +36,41 @@ jobs:
|
||||
echo "Building version: ${VERSION}"
|
||||
|
||||
- name: Update build.yaml with version
|
||||
working-directory: release-${{ github.run_id }}
|
||||
run: |
|
||||
VERSION="${{ steps.get_version.outputs.version_number }}"
|
||||
sed -i "s/^version:.*/version: \"${VERSION}\"/" build.yaml
|
||||
cat build.yaml
|
||||
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.nuget/packages
|
||||
key: nuget-${{ hashFiles('**/Jellyfin.Plugin.JellyLMS.csproj') }}
|
||||
restore-keys: nuget-
|
||||
|
||||
- name: Restore dependencies
|
||||
working-directory: release-${{ github.run_id }}
|
||||
run: dotnet restore Jellyfin.Plugin.JellyLMS.sln
|
||||
|
||||
- name: Build solution
|
||||
run: dotnet build Jellyfin.Plugin.JellyLMS.sln --configuration Release --no-restore --no-self-contained
|
||||
|
||||
- name: Install JPRM
|
||||
run: |
|
||||
python3 -m venv /tmp/jprm-venv
|
||||
/tmp/jprm-venv/bin/pip install jprm
|
||||
working-directory: release-${{ github.run_id }}
|
||||
run: dotnet build Jellyfin.Plugin.JellyLMS.sln --configuration Release --no-restore --no-self-contained /m:1
|
||||
|
||||
- name: Build Jellyfin Plugin
|
||||
id: jprm
|
||||
working-directory: release-${{ github.run_id }}
|
||||
run: |
|
||||
# Create artifacts directory for JPRM output
|
||||
mkdir -p artifacts
|
||||
|
||||
# Build plugin using JPRM
|
||||
/tmp/jprm-venv/bin/jprm --verbosity=debug plugin build ./
|
||||
|
||||
# Find the generated zip file
|
||||
ARTIFACT=$(find . -name "*.zip" -type f -print -quit)
|
||||
jprm --verbosity=debug plugin build ./
|
||||
ARTIFACT=$(find . -name "*.zip" -type f -print -quit | sed 's|^\./||')
|
||||
ARTIFACT_NAME=$(basename "${ARTIFACT}")
|
||||
echo "artifact=${ARTIFACT}" >> $GITHUB_OUTPUT
|
||||
echo "artifact_name=${ARTIFACT_NAME}" >> $GITHUB_OUTPUT
|
||||
echo "Found artifact: ${ARTIFACT}"
|
||||
|
||||
- name: Create Release
|
||||
working-directory: release-${{ github.run_id }}
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
@@ -81,22 +79,13 @@ jobs:
|
||||
REPO_NAME="${{ github.event.repository.name }}"
|
||||
GITEA_URL="${{ github.server_url }}"
|
||||
|
||||
# Prepare release body
|
||||
RELEASE_BODY="JellyLMS Jellyfin Plugin ${{ steps.get_version.outputs.version }}\n\nSee attached files for plugin installation."
|
||||
RELEASE_BODY_JSON=$(echo -n "${RELEASE_BODY}" | jq -Rs .)
|
||||
|
||||
# Create release using Gitea API
|
||||
VERSION="${{ steps.get_version.outputs.version }}"
|
||||
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/releases" \
|
||||
-d "{
|
||||
\"tag_name\": \"${{ steps.get_version.outputs.version }}\",
|
||||
\"name\": \"Release ${{ steps.get_version.outputs.version }}\",
|
||||
\"body\": ${RELEASE_BODY_JSON},
|
||||
\"draft\": false,
|
||||
\"prerelease\": false
|
||||
}")
|
||||
-d "$(jq -n --arg tag "$VERSION" --arg name "Release $VERSION" --arg body "JellyLMS Jellyfin Plugin ${VERSION}. See attached files for plugin installation." '{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')")
|
||||
|
||||
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
|
||||
BODY=$(echo "$RESPONSE" | sed '$d')
|
||||
@@ -128,3 +117,61 @@ jobs:
|
||||
|
||||
echo "Release created successfully!"
|
||||
echo "View at: ${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/releases/tag/${{ steps.get_version.outputs.version }}"
|
||||
|
||||
- name: Calculate checksum
|
||||
id: checksum
|
||||
working-directory: release-${{ github.run_id }}
|
||||
run: |
|
||||
CHECKSUM=$(md5sum "${{ steps.jprm.outputs.artifact }}" | awk '{print $1}')
|
||||
echo "checksum=${CHECKSUM}" >> $GITHUB_OUTPUT
|
||||
echo "MD5 checksum: ${CHECKSUM}"
|
||||
|
||||
- name: Update manifest.json
|
||||
working-directory: release-${{ github.run_id }}
|
||||
run: |
|
||||
git config user.name "Gitea Actions"
|
||||
git config user.email "actions@gitea.tourolle.paris"
|
||||
git fetch origin master
|
||||
git checkout master
|
||||
|
||||
VERSION="${{ steps.get_version.outputs.version_number }}"
|
||||
CHECKSUM="${{ steps.checksum.outputs.checksum }}"
|
||||
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
ARTIFACT_NAME="${{ steps.jprm.outputs.artifact_name }}"
|
||||
REPO_OWNER="${{ github.repository_owner }}"
|
||||
REPO_NAME="${{ github.event.repository.name }}"
|
||||
GITEA_URL="${{ github.server_url }}"
|
||||
DOWNLOAD_URL="${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/releases/download/${{ steps.get_version.outputs.version }}/${ARTIFACT_NAME}"
|
||||
|
||||
# Create the new version entry
|
||||
NEW_VERSION=$(cat <<EOF
|
||||
{
|
||||
"version": "${VERSION}",
|
||||
"changelog": "Release ${VERSION}",
|
||||
"targetAbi": "10.10.0.0",
|
||||
"sourceUrl": "${DOWNLOAD_URL}",
|
||||
"checksum": "${CHECKSUM}",
|
||||
"timestamp": "${TIMESTAMP}"
|
||||
}
|
||||
EOF
|
||||
)
|
||||
|
||||
# Prepend new version to the versions array in manifest.json
|
||||
jq --argjson newver "${NEW_VERSION}" '.[0].versions = [$newver] + .[0].versions' manifest.json > manifest.tmp.json
|
||||
mv manifest.tmp.json manifest.json
|
||||
|
||||
echo "Updated manifest.json:"
|
||||
cat manifest.json
|
||||
|
||||
- name: Commit and push manifest
|
||||
working-directory: release-${{ github.run_id }}
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
git add manifest.json
|
||||
git commit -m "Update manifest.json for ${{ steps.get_version.outputs.version }}"
|
||||
git push origin master
|
||||
|
||||
- name: Cleanup
|
||||
if: always()
|
||||
run: rm -rf release-${{ github.run_id }}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# JellyLMS Builder Image
|
||||
# Pre-built image with .NET SDK and JPRM for building Jellyfin plugins
|
||||
# Build: docker build -f Dockerfile.builder -t gitea.tourolle.paris/dtourolle/jellylms-builder:latest .
|
||||
# Push: docker push gitea.tourolle.paris/dtourolle/jellylms-builder:latest
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:9.0
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
python3 \
|
||||
python3-pip \
|
||||
git \
|
||||
jq \
|
||||
nodejs \
|
||||
npm \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip install --break-system-packages jprm
|
||||
|
||||
WORKDIR /src
|
||||
@@ -1,10 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Net.Mime;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Data.Enums;
|
||||
using Jellyfin.Database.Implementations.Enums;
|
||||
using Jellyfin.Plugin.JellyLMS.Models;
|
||||
using Jellyfin.Plugin.JellyLMS.Services;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.Audio;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -22,22 +30,63 @@ public class JellyLmsController : ControllerBase
|
||||
{
|
||||
private readonly ILmsApiClient _lmsClient;
|
||||
private readonly LmsPlayerManager _playerManager;
|
||||
private readonly LmsSessionManager _sessionManager;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly IUserManager _userManager;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JellyLmsController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="lmsClient">The LMS API client.</param>
|
||||
/// <param name="playerManager">The player manager.</param>
|
||||
/// <param name="sessionManager">The session manager.</param>
|
||||
/// <param name="libraryManager">The library manager.</param>
|
||||
/// <param name="userManager">The user manager.</param>
|
||||
public JellyLmsController(
|
||||
ILmsApiClient lmsClient,
|
||||
LmsPlayerManager playerManager,
|
||||
LmsSessionManager sessionManager)
|
||||
ILibraryManager libraryManager,
|
||||
IUserManager userManager)
|
||||
{
|
||||
_lmsClient = lmsClient;
|
||||
_playerManager = playerManager;
|
||||
_sessionManager = sessionManager;
|
||||
_libraryManager = libraryManager;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the current user is allowed to use the multi-room remote
|
||||
/// control features (administrators, or users granted the
|
||||
/// "Allow remote control of other users" permission).
|
||||
/// </summary>
|
||||
/// <returns><c>true</c> if the user may use remote control endpoints.</returns>
|
||||
private bool HasRemoteControlAccess()
|
||||
{
|
||||
var username = User.Identity?.Name;
|
||||
if (string.IsNullOrEmpty(username))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var user = _userManager.GetUserByName(username);
|
||||
if (user is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return HasPermission(user, PermissionKind.IsAdministrator)
|
||||
|| HasPermission(user, PermissionKind.EnableRemoteControlOfOtherUsers);
|
||||
}
|
||||
|
||||
private static bool HasPermission(Jellyfin.Database.Implementations.Entities.User user, PermissionKind kind)
|
||||
{
|
||||
foreach (var permission in user.Permissions)
|
||||
{
|
||||
if (permission.Kind == kind)
|
||||
{
|
||||
return permission.Value;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -59,8 +108,14 @@ public class JellyLmsController : ControllerBase
|
||||
/// <returns>List of players.</returns>
|
||||
[HttpGet("Players")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult<List<LmsPlayer>>> GetPlayers([FromQuery] bool refresh = false)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var players = await _playerManager.GetPlayersAsync(refresh).ConfigureAwait(false);
|
||||
return Ok(players);
|
||||
}
|
||||
@@ -72,9 +127,15 @@ public class JellyLmsController : ControllerBase
|
||||
/// <returns>The player details.</returns>
|
||||
[HttpGet("Players/{mac}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<LmsPlayer>> GetPlayer(string mac)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var player = await _playerManager.GetPlayerAsync(mac).ConfigureAwait(false);
|
||||
if (player == null)
|
||||
{
|
||||
@@ -92,8 +153,14 @@ public class JellyLmsController : ControllerBase
|
||||
[HttpPost("Players/{mac}/PowerOn")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult> PowerOn(string mac)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var success = await _lmsClient.PowerOnAsync(mac).ConfigureAwait(false);
|
||||
return success ? Ok() : BadRequest("Failed to power on player");
|
||||
}
|
||||
@@ -106,8 +173,14 @@ public class JellyLmsController : ControllerBase
|
||||
[HttpPost("Players/{mac}/PowerOff")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult> PowerOff(string mac)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var success = await _lmsClient.PowerOffAsync(mac).ConfigureAwait(false);
|
||||
return success ? Ok() : BadRequest("Failed to power off player");
|
||||
}
|
||||
@@ -121,8 +194,14 @@ public class JellyLmsController : ControllerBase
|
||||
[HttpPost("Players/{mac}/Volume")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult> SetVolume(string mac, [FromBody] VolumeRequest request)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var success = await _lmsClient.SetVolumeAsync(mac, request.Volume).ConfigureAwait(false);
|
||||
return success ? Ok() : BadRequest("Failed to set volume");
|
||||
}
|
||||
@@ -133,8 +212,14 @@ public class JellyLmsController : ControllerBase
|
||||
/// <returns>List of sync groups.</returns>
|
||||
[HttpGet("SyncGroups")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult<List<SyncGroup>>> GetSyncGroups()
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var groups = await _playerManager.GetSyncGroupsAsync().ConfigureAwait(false);
|
||||
return Ok(groups);
|
||||
}
|
||||
@@ -147,8 +232,14 @@ public class JellyLmsController : ControllerBase
|
||||
[HttpPost("SyncGroups")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult> CreateSyncGroup([FromBody] CreateSyncGroupRequest request)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var success = await _playerManager.CreateSyncGroupAsync(request.MasterMac, request.SlaveMacs)
|
||||
.ConfigureAwait(false);
|
||||
return success ? Ok() : BadRequest("Failed to create sync group");
|
||||
@@ -162,8 +253,14 @@ public class JellyLmsController : ControllerBase
|
||||
[HttpDelete("SyncGroups/Players/{mac}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult> UnsyncPlayer(string mac)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var success = await _playerManager.UnsyncPlayerAsync(mac).ConfigureAwait(false);
|
||||
return success ? Ok() : BadRequest("Failed to unsync player");
|
||||
}
|
||||
@@ -176,115 +273,147 @@ public class JellyLmsController : ControllerBase
|
||||
[HttpDelete("SyncGroups/{masterMac}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<ActionResult> DissolveSyncGroup(string masterMac)
|
||||
{
|
||||
if (!HasRemoteControlAccess())
|
||||
{
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var success = await _playerManager.DissolveSyncGroupAsync(masterMac).ConfigureAwait(false);
|
||||
return success ? Ok() : BadRequest("Failed to dissolve sync group");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all active playback sessions.
|
||||
/// Checks whether the current user is allowed to use the multi-room remote control.
|
||||
/// Used by the remote control page and the injected web client button to decide
|
||||
/// whether to show themselves.
|
||||
/// </summary>
|
||||
/// <returns>List of active sessions.</returns>
|
||||
[HttpGet("Sessions")]
|
||||
/// <returns>200 OK if allowed, otherwise 403 Forbidden.</returns>
|
||||
[HttpGet("RemoteControl/Access")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public ActionResult<List<LmsPlaybackSession>> GetSessions()
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public ActionResult CheckRemoteControlAccess()
|
||||
{
|
||||
return Ok(_sessionManager.GetActiveSessions());
|
||||
return HasRemoteControlAccess() ? Ok() : Forbid();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts playback of a Jellyfin item on LMS players.
|
||||
/// Serves the standalone multi-room remote control page. The page itself contains
|
||||
/// no sensitive data; it authenticates API calls using the Jellyfin access token
|
||||
/// stored by the web client, so it is reachable without a prior Jellyfin auth header.
|
||||
/// </summary>
|
||||
/// <param name="request">The playback request.</param>
|
||||
/// <returns>The created session.</returns>
|
||||
[HttpPost("Sessions/Play")]
|
||||
/// <returns>The remote control HTML page.</returns>
|
||||
[HttpGet("RemoteControl")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<ActionResult<LmsPlaybackSession>> StartPlayback([FromBody] StartPlaybackRequest request)
|
||||
public ActionResult GetRemoteControlPage()
|
||||
{
|
||||
var session = await _sessionManager.StartPlaybackAsync(request.ItemId, request.PlayerMacs, request.UserId)
|
||||
.ConfigureAwait(false);
|
||||
return ServeEmbeddedResource("Jellyfin.Plugin.JellyLMS.Web.RemoteControl.html", "text/html");
|
||||
}
|
||||
|
||||
if (session == null)
|
||||
/// <summary>
|
||||
/// Serves the client script that is injected into the Jellyfin web client to add a
|
||||
/// floating button linking to the remote control page.
|
||||
/// </summary>
|
||||
/// <returns>The client script.</returns>
|
||||
[HttpGet("RemoteControl/ClientScript")]
|
||||
[AllowAnonymous]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public ActionResult GetRemoteControlClientScript()
|
||||
{
|
||||
return ServeEmbeddedResource("Jellyfin.Plugin.JellyLMS.Web.remote-button.js", "application/javascript");
|
||||
}
|
||||
|
||||
private FileStreamResult ServeEmbeddedResource(string resourceName, string contentType)
|
||||
{
|
||||
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)
|
||||
?? throw new InvalidOperationException($"Embedded resource '{resourceName}' not found.");
|
||||
|
||||
return File(stream, contentType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovers file paths used by Jellyfin's music libraries.
|
||||
/// Helps users configure path mappings for direct file access.
|
||||
/// </summary>
|
||||
/// <returns>Sample file paths from each music library.</returns>
|
||||
[HttpGet("DiscoverPaths")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public ActionResult<DiscoveredPathsResponse> DiscoverPaths()
|
||||
{
|
||||
var response = new DiscoveredPathsResponse();
|
||||
|
||||
// Get sample audio files from the library
|
||||
var query = new InternalItemsQuery
|
||||
{
|
||||
return BadRequest("Failed to start playback");
|
||||
IncludeItemTypes = [BaseItemKind.Audio],
|
||||
Limit = 50,
|
||||
Recursive = true
|
||||
};
|
||||
|
||||
var items = _libraryManager.GetItemsResult(query).Items;
|
||||
|
||||
// Extract unique path prefixes
|
||||
var pathPrefixes = new HashSet<string>();
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (string.IsNullOrEmpty(item.Path))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add sample paths
|
||||
if (response.SamplePaths.Count < 5)
|
||||
{
|
||||
response.SamplePaths.Add(item.Path);
|
||||
}
|
||||
|
||||
// Try to find common path prefixes
|
||||
var path = item.Path.Replace('\\', '/');
|
||||
var parts = path.Split('/');
|
||||
|
||||
// Build prefix from first few directory levels
|
||||
if (parts.Length > 2)
|
||||
{
|
||||
// Try different prefix lengths to find common ones
|
||||
for (var i = 2; i <= Math.Min(4, parts.Length - 1); i++)
|
||||
{
|
||||
var prefix = string.Join('/', parts.Take(i));
|
||||
if (!string.IsNullOrEmpty(prefix) && !prefix.Contains('.', StringComparison.Ordinal))
|
||||
{
|
||||
pathPrefixes.Add(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(session);
|
||||
// Sort prefixes by length (shorter = more general)
|
||||
response.DetectedPrefixes = pathPrefixes
|
||||
.OrderBy(p => p.Length)
|
||||
.Take(10)
|
||||
.ToList();
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Response containing discovered file paths from Jellyfin libraries.
|
||||
/// </summary>
|
||||
public class DiscoveredPathsResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets sample file paths from the music library.
|
||||
/// </summary>
|
||||
public List<string> SamplePaths { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Pauses a playback session.
|
||||
/// Gets or sets detected common path prefixes.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>Success status.</returns>
|
||||
[HttpPost("Sessions/{sessionId}/Pause")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> PauseSession(string sessionId)
|
||||
{
|
||||
var success = await _sessionManager.PauseSessionAsync(sessionId).ConfigureAwait(false);
|
||||
return success ? Ok() : NotFound();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resumes a paused playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>Success status.</returns>
|
||||
[HttpPost("Sessions/{sessionId}/Resume")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> ResumeSession(string sessionId)
|
||||
{
|
||||
var success = await _sessionManager.ResumeSessionAsync(sessionId).ConfigureAwait(false);
|
||||
return success ? Ok() : NotFound();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops a playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>Success status.</returns>
|
||||
[HttpPost("Sessions/{sessionId}/Stop")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> StopSession(string sessionId)
|
||||
{
|
||||
var success = await _sessionManager.StopSessionAsync(sessionId).ConfigureAwait(false);
|
||||
return success ? Ok() : NotFound();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeks to a position in the playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <param name="request">The seek request.</param>
|
||||
/// <returns>Success status.</returns>
|
||||
[HttpPost("Sessions/{sessionId}/Seek")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> SeekSession(string sessionId, [FromBody] SeekRequest request)
|
||||
{
|
||||
var success = await _sessionManager.SeekAsync(sessionId, request.PositionTicks).ConfigureAwait(false);
|
||||
return success ? Ok() : NotFound();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the volume for all players in a session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <param name="request">The volume request.</param>
|
||||
/// <returns>Success status.</returns>
|
||||
[HttpPost("Sessions/{sessionId}/Volume")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> SetSessionVolume(string sessionId, [FromBody] VolumeRequest request)
|
||||
{
|
||||
var success = await _sessionManager.SetVolumeAsync(sessionId, request.Volume).ConfigureAwait(false);
|
||||
return success ? Ok() : NotFound();
|
||||
}
|
||||
public List<string> DetectedPrefixes { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -316,37 +445,3 @@ public class CreateSyncGroupRequest
|
||||
[Required]
|
||||
public List<string> SlaveMacs { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request to start playback.
|
||||
/// </summary>
|
||||
public class StartPlaybackRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the Jellyfin item ID.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public Guid ItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the LMS player MAC addresses.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public List<string> PlayerMacs { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the optional user ID.
|
||||
/// </summary>
|
||||
public Guid? UserId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request to seek to a position.
|
||||
/// </summary>
|
||||
public class SeekRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the position in ticks.
|
||||
/// </summary>
|
||||
public long PositionTicks { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,24 @@
|
||||
using System.Collections.Generic;
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace Jellyfin.Plugin.JellyLMS.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a path mapping between Jellyfin and LMS file paths.
|
||||
/// </summary>
|
||||
public class PathMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the path prefix as seen by Jellyfin.
|
||||
/// </summary>
|
||||
public string JellyfinPath { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the same path prefix as seen by LMS.
|
||||
/// </summary>
|
||||
public string LmsPath { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plugin configuration for JellyLMS.
|
||||
/// </summary>
|
||||
@@ -19,6 +36,7 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
ConnectionTimeoutSeconds = 10;
|
||||
EnableAutoSync = true;
|
||||
DefaultPlayerMac = string.Empty;
|
||||
EnableHomeScreenButton = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -58,8 +76,86 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
/// </summary>
|
||||
public string DefaultPlayerMac { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether a floating "Remote" button linking to the
|
||||
/// multi-room remote control page should be injected into the Jellyfin web client.
|
||||
/// </summary>
|
||||
public bool EnableHomeScreenButton { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Jellyfin API key for authenticating stream requests from LMS.
|
||||
/// </summary>
|
||||
public string JellyfinApiKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether to use direct file paths instead of HTTP streaming.
|
||||
/// When enabled, LMS accesses files directly from shared storage, enabling native seeking.
|
||||
/// </summary>
|
||||
public bool UseDirectFilePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media path prefix as seen by Jellyfin.
|
||||
/// Used for path mapping when UseDirectFilePath is enabled.
|
||||
/// Deprecated: Use PathMappings instead. Kept for backwards compatibility.
|
||||
/// </summary>
|
||||
public string JellyfinMediaPath { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the media path prefix as seen by LMS.
|
||||
/// Used for path mapping when UseDirectFilePath is enabled.
|
||||
/// Deprecated: Use PathMappings instead. Kept for backwards compatibility.
|
||||
/// </summary>
|
||||
public string LmsMediaPath { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of path mappings between Jellyfin and LMS.
|
||||
/// Each mapping allows files from different locations to be played via direct file access.
|
||||
/// </summary>
|
||||
public List<PathMapping> PathMappings { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the timeout in seconds when waiting for LMS to start playback.
|
||||
/// </summary>
|
||||
public int LoadingTimeoutSeconds { get; set; } = 5;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the timeout in seconds when waiting for a seek operation to complete.
|
||||
/// </summary>
|
||||
public int SeekTimeoutSeconds { get; set; } = 3;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the polling interval in milliseconds during state transitions.
|
||||
/// </summary>
|
||||
public int TransitionPollIntervalMs { get; set; } = 300;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of automatic retries for transient failures.
|
||||
/// </summary>
|
||||
public int MaxAutoRetries { get; set; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// Gets all effective path mappings, including legacy single mapping if configured.
|
||||
/// </summary>
|
||||
/// <returns>Enumerable of all configured path mappings.</returns>
|
||||
public IEnumerable<PathMapping> GetAllPathMappings()
|
||||
{
|
||||
// Return configured list mappings first
|
||||
foreach (var mapping in PathMappings)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(mapping.JellyfinPath) && !string.IsNullOrEmpty(mapping.LmsPath))
|
||||
{
|
||||
yield return mapping;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to legacy single mapping for backwards compatibility
|
||||
if (!string.IsNullOrEmpty(JellyfinMediaPath) && !string.IsNullOrEmpty(LmsMediaPath))
|
||||
{
|
||||
yield return new PathMapping
|
||||
{
|
||||
JellyfinPath = JellyfinMediaPath,
|
||||
LmsPath = LmsMediaPath
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,64 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>JellyLMS</title>
|
||||
<style>
|
||||
.sync-group {
|
||||
border: 2px solid #00a4dc;
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
margin-bottom: 12px;
|
||||
background: rgba(0, 164, 220, 0.05);
|
||||
}
|
||||
.sync-group-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.sync-group-players {
|
||||
color: #ccc;
|
||||
}
|
||||
.player-sync-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid #333;
|
||||
}
|
||||
.player-sync-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.player-sync-checkbox {
|
||||
margin-right: 12px;
|
||||
}
|
||||
.player-sync-name {
|
||||
flex: 1;
|
||||
font-weight: 500;
|
||||
}
|
||||
.player-sync-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: #888;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.status-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.status-dot.on { background: #52b54b; }
|
||||
.status-dot.standby { background: #f9a825; }
|
||||
.status-dot.off { background: #f44336; }
|
||||
.sync-actions {
|
||||
margin-top: 15px;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
#syncStatus {
|
||||
margin-left: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="JellyLmsConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
|
||||
@@ -73,18 +131,6 @@
|
||||
</label>
|
||||
<div class="fieldDescription checkboxFieldDescription">Automatically sync players when playing to multiple devices</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="verticalSection">
|
||||
<h3>LMS Players</h3>
|
||||
<div id="playersList">
|
||||
<p>Click "Refresh Players" to discover LMS players.</p>
|
||||
</div>
|
||||
<div>
|
||||
<button is="emby-button" type="button" id="btnRefreshPlayers" class="raised button-alt block emby-button">
|
||||
<span>Refresh Players</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="inputContainer" style="margin-top: 15px;">
|
||||
<label class="inputLabel inputLabelUnfocused" for="DefaultPlayerMac">Default Player</label>
|
||||
@@ -96,15 +142,79 @@
|
||||
</div>
|
||||
|
||||
<div class="verticalSection">
|
||||
<h3>Player Sync Management</h3>
|
||||
<p>Manage synchronized playback groups for multi-room audio.</p>
|
||||
<div>
|
||||
<a is="emby-button" href="configurationpage?name=JellyLMS%20Sync" class="raised button-alt block emby-button" style="display: inline-block; text-decoration: none;">
|
||||
<span>Open Sync Manager</span>
|
||||
</a>
|
||||
<h3>Direct File Access (Optional)</h3>
|
||||
<p class="fieldDescription">If LMS and Jellyfin share the same storage (e.g., NAS), enable direct file access for native seeking support. This provides smooth seeking without audio restart.</p>
|
||||
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="UseDirectFilePath" name="UseDirectFilePath" type="checkbox" is="emby-checkbox" />
|
||||
<span>Enable Direct File Access</span>
|
||||
</label>
|
||||
<div class="fieldDescription checkboxFieldDescription">When enabled, LMS will access files directly instead of streaming via HTTP</div>
|
||||
</div>
|
||||
<div class="fieldDescription" style="margin-top: 10px;">
|
||||
Users can access this page directly at: <code>/web/configurationpage?name=JellyLMS%20Sync</code>
|
||||
|
||||
<div id="directPathSettings" style="margin-top: 15px;">
|
||||
<h4 style="margin-bottom: 10px;">Path Mappings</h4>
|
||||
<p class="fieldDescription">Map Jellyfin paths to LMS paths. Add multiple mappings if your music and podcasts are in different locations.</p>
|
||||
|
||||
<div style="margin-bottom: 15px;">
|
||||
<button is="emby-button" type="button" id="btnDiscoverPaths" class="raised button-alt emby-button">
|
||||
<span>Discover Jellyfin Paths</span>
|
||||
</button>
|
||||
<span id="discoverStatus" style="margin-left: 10px;"></span>
|
||||
</div>
|
||||
|
||||
<div id="discoveredPaths" style="display: none; margin-bottom: 15px; padding: 10px; background: rgba(0,0,0,0.2); border-radius: 4px;">
|
||||
<strong>Detected Jellyfin paths:</strong>
|
||||
<ul id="detectedPrefixList" style="margin: 5px 0; padding-left: 20px;"></ul>
|
||||
<div class="fieldDescription">Click a path to use it as the Jellyfin path in a new mapping</div>
|
||||
</div>
|
||||
|
||||
<div id="pathMappingsList">
|
||||
<!-- Dynamic path mappings will be added here -->
|
||||
</div>
|
||||
|
||||
<div style="margin-top: 10px;">
|
||||
<button is="emby-button" type="button" id="btnAddMapping" class="raised button-alt emby-button">
|
||||
<span>+ Add Mapping</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="verticalSection">
|
||||
<h3>Multi-Room Remote</h3>
|
||||
<p class="fieldDescription">A standalone remote control page is available at <code>/JellyLms/RemoteControl</code> for any user granted the "Allow remote control of other users" permission (Dashboard > Users).</p>
|
||||
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="EnableHomeScreenButton" name="EnableHomeScreenButton" type="checkbox" is="emby-checkbox" />
|
||||
<span>Show floating Remote button in web client</span>
|
||||
</label>
|
||||
<div class="fieldDescription checkboxFieldDescription">Adds a floating button to the Jellyfin web client that links to the remote control page (for authorized users only). Requires write access to the Jellyfin web root and a page reload to take effect.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="verticalSection">
|
||||
<h3>Player Sync</h3>
|
||||
<p class="fieldDescription">Select players to sync together for multi-room audio. Synced players play in perfect sync.</p>
|
||||
|
||||
<div id="currentSyncGroups">
|
||||
<!-- Existing sync groups shown here -->
|
||||
</div>
|
||||
|
||||
<div id="playerSyncList">
|
||||
<p>Loading players...</p>
|
||||
</div>
|
||||
|
||||
<div class="sync-actions">
|
||||
<button is="emby-button" type="button" id="btnSyncSelected" class="raised button-submit emby-button" disabled>
|
||||
<span>Sync Selected</span>
|
||||
</button>
|
||||
<button is="emby-button" type="button" id="btnRefreshPlayers" class="raised button-alt emby-button">
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
<span id="syncStatus"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -118,45 +228,34 @@
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
var JellyLmsConfig = {
|
||||
pluginUniqueId: 'a5b8c9d0-1e2f-3a4b-5c6d-7e8f9a0b1c2d'
|
||||
pluginUniqueId: 'a5b8c9d0-1e2f-3a4b-5c6d-7e8f9a0b1c2d',
|
||||
players: [],
|
||||
syncGroups: []
|
||||
};
|
||||
|
||||
function getStatusClass(player) {
|
||||
if (!player.IsConnected) return 'off';
|
||||
return player.IsPoweredOn ? 'on' : 'standby';
|
||||
}
|
||||
|
||||
function getStatusText(player) {
|
||||
if (!player.IsConnected) return 'Disconnected';
|
||||
return player.IsPoweredOn ? 'On' : 'Standby';
|
||||
}
|
||||
|
||||
function loadPlayers() {
|
||||
var playersList = document.querySelector('#playersList');
|
||||
var defaultSelect = document.querySelector('#DefaultPlayerMac');
|
||||
var currentDefault = defaultSelect.value;
|
||||
|
||||
playersList.innerHTML = '<p>Loading players...</p>';
|
||||
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/Players', { refresh: true }),
|
||||
type: 'GET',
|
||||
dataType: 'json'
|
||||
}).then(function(players) {
|
||||
JellyLmsConfig.players = players || [];
|
||||
defaultSelect.innerHTML = '<option value="">None</option>';
|
||||
|
||||
if (!players || players.length === 0) {
|
||||
playersList.innerHTML = '<p>No players found. Make sure LMS is running and has connected players.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '<table class="tblGenres detailTable" style="width: 100%;">';
|
||||
html += '<thead><tr><th>Name</th><th>Model</th><th>Status</th><th>Volume</th><th>Synced</th></tr></thead>';
|
||||
html += '<tbody>';
|
||||
|
||||
players.forEach(function(player) {
|
||||
var status = player.IsConnected ? (player.IsPoweredOn ? 'On' : 'Standby') : 'Disconnected';
|
||||
var statusColor = player.IsConnected ? (player.IsPoweredOn ? 'green' : 'orange') : 'red';
|
||||
var syncStatus = player.IsSynced ? 'Yes' : 'No';
|
||||
|
||||
html += '<tr>';
|
||||
html += '<td>' + player.Name + '</td>';
|
||||
html += '<td>' + player.Model + '</td>';
|
||||
html += '<td style="color: ' + statusColor + ';">' + status + '</td>';
|
||||
html += '<td>' + player.Volume + '%</td>';
|
||||
html += '<td>' + syncStatus + '</td>';
|
||||
html += '</tr>';
|
||||
|
||||
var option = document.createElement('option');
|
||||
option.value = player.MacAddress;
|
||||
option.text = player.Name;
|
||||
@@ -166,14 +265,179 @@
|
||||
defaultSelect.appendChild(option);
|
||||
});
|
||||
|
||||
html += '</tbody></table>';
|
||||
playersList.innerHTML = html;
|
||||
renderPlayerList();
|
||||
}).catch(function(err) {
|
||||
playersList.innerHTML = '<p style="color: red;">Error loading players. Check LMS connection.</p>';
|
||||
document.querySelector('#playerSyncList').innerHTML = '<p style="color: red;">Error loading players. Check LMS connection.</p>';
|
||||
console.error('Error loading players:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function loadSyncGroups() {
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups'),
|
||||
type: 'GET',
|
||||
dataType: 'json'
|
||||
}).then(function(groups) {
|
||||
JellyLmsConfig.syncGroups = groups || [];
|
||||
renderSyncGroups();
|
||||
renderPlayerList();
|
||||
}).catch(function(err) {
|
||||
console.error('Error loading sync groups:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function renderSyncGroups() {
|
||||
var container = document.querySelector('#currentSyncGroups');
|
||||
var groups = JellyLmsConfig.syncGroups;
|
||||
|
||||
if (!groups || groups.length === 0) {
|
||||
container.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
groups.forEach(function(group) {
|
||||
var playerNames = [];
|
||||
var masterPlayer = JellyLmsConfig.players.find(function(p) { return p.MacAddress === group.MasterMac; });
|
||||
if (masterPlayer) playerNames.push(masterPlayer.Name);
|
||||
|
||||
group.SlaveMacs.forEach(function(mac) {
|
||||
var player = JellyLmsConfig.players.find(function(p) { return p.MacAddress === mac; });
|
||||
if (player) playerNames.push(player.Name);
|
||||
});
|
||||
|
||||
html += '<div class="sync-group">';
|
||||
html += '<div class="sync-group-header">';
|
||||
html += '<span class="sync-group-players">' + playerNames.join(' + ') + '</span>';
|
||||
html += '<button is="emby-button" type="button" class="raised button-alt emby-button btnUnsyncGroup" data-master="' + group.MasterMac + '">';
|
||||
html += '<span>Unsync</span>';
|
||||
html += '</button>';
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
|
||||
container.querySelectorAll('.btnUnsyncGroup').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
unsyncGroup(this.getAttribute('data-master'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderPlayerList() {
|
||||
var container = document.querySelector('#playerSyncList');
|
||||
var players = JellyLmsConfig.players;
|
||||
|
||||
if (!players || players.length === 0) {
|
||||
container.innerHTML = '<p>No players found. Make sure LMS is running.</p>';
|
||||
updateSyncButton();
|
||||
return;
|
||||
}
|
||||
|
||||
// Get MACs of already synced players
|
||||
var syncedMacs = new Set();
|
||||
JellyLmsConfig.syncGroups.forEach(function(group) {
|
||||
syncedMacs.add(group.MasterMac);
|
||||
group.SlaveMacs.forEach(function(mac) { syncedMacs.add(mac); });
|
||||
});
|
||||
|
||||
// Only show unsynced players
|
||||
var unsyncedPlayers = players.filter(function(p) {
|
||||
return !syncedMacs.has(p.MacAddress);
|
||||
});
|
||||
|
||||
if (unsyncedPlayers.length === 0) {
|
||||
container.innerHTML = '<p>All players are synced.</p>';
|
||||
updateSyncButton();
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
unsyncedPlayers.forEach(function(player) {
|
||||
var statusClass = getStatusClass(player);
|
||||
html += '<div class="player-sync-row">';
|
||||
html += '<input type="checkbox" class="player-sync-checkbox" data-mac="' + player.MacAddress + '" id="sync-' + player.MacAddress + '">';
|
||||
html += '<label class="player-sync-name" for="sync-' + player.MacAddress + '">' + player.Name + '</label>';
|
||||
html += '<div class="player-sync-status">';
|
||||
html += '<span class="status-dot ' + statusClass + '"></span>';
|
||||
html += '<span>' + getStatusText(player) + '</span>';
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
|
||||
// Add change listeners
|
||||
container.querySelectorAll('.player-sync-checkbox').forEach(function(cb) {
|
||||
cb.addEventListener('change', updateSyncButton);
|
||||
});
|
||||
|
||||
updateSyncButton();
|
||||
}
|
||||
|
||||
function getSelectedMacs() {
|
||||
var checkboxes = document.querySelectorAll('.player-sync-checkbox:checked');
|
||||
var macs = [];
|
||||
checkboxes.forEach(function(cb) {
|
||||
macs.push(cb.getAttribute('data-mac'));
|
||||
});
|
||||
return macs;
|
||||
}
|
||||
|
||||
function updateSyncButton() {
|
||||
var btn = document.querySelector('#btnSyncSelected');
|
||||
var selected = getSelectedMacs();
|
||||
btn.disabled = selected.length < 2;
|
||||
}
|
||||
|
||||
function syncSelected() {
|
||||
var macs = getSelectedMacs();
|
||||
if (macs.length < 2) return;
|
||||
|
||||
var statusDiv = document.querySelector('#syncStatus');
|
||||
statusDiv.innerHTML = '<span style="color: orange;">Syncing...</span>';
|
||||
|
||||
// First MAC becomes master (arbitrary, user doesn't need to know)
|
||||
var masterMac = macs[0];
|
||||
var slaveMacs = macs.slice(1);
|
||||
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups'),
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
MasterMac: masterMac,
|
||||
SlaveMacs: slaveMacs
|
||||
})
|
||||
}).then(function() {
|
||||
statusDiv.innerHTML = '<span style="color: green;">Synced!</span>';
|
||||
setTimeout(function() {
|
||||
statusDiv.innerHTML = '';
|
||||
loadSyncGroups();
|
||||
}, 1500);
|
||||
}).catch(function(err) {
|
||||
statusDiv.innerHTML = '<span style="color: red;">Failed to sync.</span>';
|
||||
console.error('Error syncing:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function unsyncGroup(masterMac) {
|
||||
var statusDiv = document.querySelector('#syncStatus');
|
||||
statusDiv.innerHTML = '<span style="color: orange;">Unsyncing...</span>';
|
||||
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups/' + encodeURIComponent(masterMac)),
|
||||
type: 'DELETE'
|
||||
}).then(function() {
|
||||
statusDiv.innerHTML = '';
|
||||
loadSyncGroups();
|
||||
}).catch(function(err) {
|
||||
statusDiv.innerHTML = '<span style="color: red;">Failed to unsync.</span>';
|
||||
console.error('Error unsyncing:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function testConnection() {
|
||||
var statusDiv = document.querySelector('#connectionStatus');
|
||||
statusDiv.innerHTML = '<span style="color: orange;">Testing connection...</span>';
|
||||
@@ -186,6 +450,7 @@
|
||||
if (result.IsConnected) {
|
||||
statusDiv.innerHTML = '<span style="color: green;">Connected! Found ' + result.PlayerCount + ' player(s).</span>';
|
||||
loadPlayers();
|
||||
loadSyncGroups();
|
||||
} else {
|
||||
statusDiv.innerHTML = '<span style="color: red;">Connection failed: ' + (result.LastError || 'Unknown error') + '</span>';
|
||||
}
|
||||
@@ -195,6 +460,113 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Path Mapping Functions
|
||||
function renderPathMappings(mappings) {
|
||||
var container = document.querySelector('#pathMappingsList');
|
||||
if (!mappings || mappings.length === 0) {
|
||||
container.innerHTML = '<p class="fieldDescription">No path mappings configured. Click "Discover Jellyfin Paths" to get started.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
mappings.forEach(function(mapping, index) {
|
||||
html += '<div class="path-mapping-row" style="display: flex; gap: 10px; align-items: flex-end; margin-bottom: 10px; padding: 10px; background: rgba(0,0,0,0.1); border-radius: 4px;">';
|
||||
html += '<div style="flex: 1;">';
|
||||
html += '<label class="inputLabel inputLabelUnfocused">Jellyfin Path</label>';
|
||||
html += '<input type="text" is="emby-input" class="mapping-jellyfin-path" data-index="' + index + '" value="' + (mapping.JellyfinPath || '') + '" placeholder="/media/music" />';
|
||||
html += '</div>';
|
||||
html += '<div style="flex: 1;">';
|
||||
html += '<label class="inputLabel inputLabelUnfocused">LMS Path</label>';
|
||||
html += '<input type="text" is="emby-input" class="mapping-lms-path" data-index="' + index + '" value="' + (mapping.LmsPath || '') + '" placeholder="/mnt/music" />';
|
||||
html += '</div>';
|
||||
html += '<button is="emby-button" type="button" class="raised button-alt emby-button btnRemoveMapping" data-index="' + index + '" style="margin-bottom: 0;">';
|
||||
html += '<span>Remove</span>';
|
||||
html += '</button>';
|
||||
html += '</div>';
|
||||
});
|
||||
container.innerHTML = html;
|
||||
|
||||
// Add remove handlers
|
||||
container.querySelectorAll('.btnRemoveMapping').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
var idx = parseInt(this.getAttribute('data-index'));
|
||||
JellyLmsConfig.pathMappings.splice(idx, 1);
|
||||
renderPathMappings(JellyLmsConfig.pathMappings);
|
||||
});
|
||||
});
|
||||
|
||||
// Update stored mappings when inputs change
|
||||
container.querySelectorAll('.mapping-jellyfin-path, .mapping-lms-path').forEach(function(input) {
|
||||
input.addEventListener('change', function() {
|
||||
var idx = parseInt(this.getAttribute('data-index'));
|
||||
if (this.classList.contains('mapping-jellyfin-path')) {
|
||||
JellyLmsConfig.pathMappings[idx].JellyfinPath = this.value;
|
||||
} else {
|
||||
JellyLmsConfig.pathMappings[idx].LmsPath = this.value;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addPathMapping(jellyfinPath, lmsPath) {
|
||||
JellyLmsConfig.pathMappings = JellyLmsConfig.pathMappings || [];
|
||||
JellyLmsConfig.pathMappings.push({
|
||||
JellyfinPath: jellyfinPath || '',
|
||||
LmsPath: lmsPath || ''
|
||||
});
|
||||
renderPathMappings(JellyLmsConfig.pathMappings);
|
||||
}
|
||||
|
||||
function discoverPaths() {
|
||||
var statusDiv = document.querySelector('#discoverStatus');
|
||||
statusDiv.innerHTML = '<span style="color: orange;">Discovering...</span>';
|
||||
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/DiscoverPaths'),
|
||||
type: 'GET',
|
||||
dataType: 'json'
|
||||
}).then(function(result) {
|
||||
statusDiv.innerHTML = '';
|
||||
var discoveredDiv = document.querySelector('#discoveredPaths');
|
||||
var prefixList = document.querySelector('#detectedPrefixList');
|
||||
|
||||
if (result.DetectedPrefixes && result.DetectedPrefixes.length > 0) {
|
||||
discoveredDiv.style.display = 'block';
|
||||
var html = '';
|
||||
result.DetectedPrefixes.forEach(function(prefix) {
|
||||
html += '<li><a href="#" class="detected-prefix-link" data-path="' + prefix + '" style="color: #00a4dc;">' + prefix + '</a></li>';
|
||||
});
|
||||
prefixList.innerHTML = html;
|
||||
|
||||
// Add click handlers to use detected paths
|
||||
prefixList.querySelectorAll('.detected-prefix-link').forEach(function(link) {
|
||||
link.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
addPathMapping(this.getAttribute('data-path'), '');
|
||||
});
|
||||
});
|
||||
} else {
|
||||
discoveredDiv.style.display = 'block';
|
||||
prefixList.innerHTML = '<li>No audio files found in library</li>';
|
||||
}
|
||||
}).catch(function(err) {
|
||||
statusDiv.innerHTML = '<span style="color: red;">Discovery failed</span>';
|
||||
console.error('Path discovery failed:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function getPathMappingsFromUI() {
|
||||
var mappings = [];
|
||||
document.querySelectorAll('.path-mapping-row').forEach(function(row) {
|
||||
var jellyfinPath = row.querySelector('.mapping-jellyfin-path').value;
|
||||
var lmsPath = row.querySelector('.mapping-lms-path').value;
|
||||
if (jellyfinPath || lmsPath) {
|
||||
mappings.push({ JellyfinPath: jellyfinPath, LmsPath: lmsPath });
|
||||
}
|
||||
});
|
||||
return mappings;
|
||||
}
|
||||
|
||||
document.querySelector('#JellyLmsConfigPage')
|
||||
.addEventListener('pageshow', function() {
|
||||
Dashboard.showLoadingMsg();
|
||||
@@ -207,7 +579,24 @@
|
||||
document.querySelector('#ConnectionTimeoutSeconds').value = config.ConnectionTimeoutSeconds || 10;
|
||||
document.querySelector('#EnableAutoSync').checked = config.EnableAutoSync !== false;
|
||||
document.querySelector('#DefaultPlayerMac').value = config.DefaultPlayerMac || '';
|
||||
document.querySelector('#UseDirectFilePath').checked = config.UseDirectFilePath || false;
|
||||
document.querySelector('#EnableHomeScreenButton').checked = config.EnableHomeScreenButton !== false;
|
||||
|
||||
// Load path mappings (new list format, with fallback to legacy single mapping)
|
||||
JellyLmsConfig.pathMappings = config.PathMappings || [];
|
||||
// If no list mappings but legacy single mapping exists, show it
|
||||
if (JellyLmsConfig.pathMappings.length === 0 && config.JellyfinMediaPath && config.LmsMediaPath) {
|
||||
JellyLmsConfig.pathMappings = [{
|
||||
JellyfinPath: config.JellyfinMediaPath,
|
||||
LmsPath: config.LmsMediaPath
|
||||
}];
|
||||
}
|
||||
renderPathMappings(JellyLmsConfig.pathMappings);
|
||||
|
||||
Dashboard.hideLoadingMsg();
|
||||
|
||||
loadPlayers();
|
||||
loadSyncGroups();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -226,6 +615,12 @@
|
||||
document.querySelector('#btnRefreshPlayers')
|
||||
.addEventListener('click', function() {
|
||||
loadPlayers();
|
||||
loadSyncGroups();
|
||||
});
|
||||
|
||||
document.querySelector('#btnSyncSelected')
|
||||
.addEventListener('click', function() {
|
||||
syncSelected();
|
||||
});
|
||||
|
||||
document.querySelector('#JellyLmsConfigForm')
|
||||
@@ -240,6 +635,12 @@
|
||||
config.ConnectionTimeoutSeconds = parseInt(document.querySelector('#ConnectionTimeoutSeconds').value) || 10;
|
||||
config.EnableAutoSync = document.querySelector('#EnableAutoSync').checked;
|
||||
config.DefaultPlayerMac = document.querySelector('#DefaultPlayerMac').value;
|
||||
config.UseDirectFilePath = document.querySelector('#UseDirectFilePath').checked;
|
||||
config.EnableHomeScreenButton = document.querySelector('#EnableHomeScreenButton').checked;
|
||||
// Save path mappings (clear legacy single mapping when using list)
|
||||
config.PathMappings = getPathMappingsFromUI();
|
||||
config.JellyfinMediaPath = '';
|
||||
config.LmsMediaPath = '';
|
||||
ApiClient.updatePluginConfiguration(JellyLmsConfig.pluginUniqueId, config).then(function (result) {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
});
|
||||
@@ -248,6 +649,16 @@
|
||||
e.preventDefault();
|
||||
return false;
|
||||
});
|
||||
|
||||
document.querySelector('#btnDiscoverPaths')
|
||||
.addEventListener('click', function() {
|
||||
discoverPaths();
|
||||
});
|
||||
|
||||
document.querySelector('#btnAddMapping')
|
||||
.addEventListener('click', function() {
|
||||
addPathMapping('', '');
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
@@ -1,490 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LMS Player Sync</title>
|
||||
<style>
|
||||
.sync-container {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.player-card {
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
padding: 15px;
|
||||
min-width: 200px;
|
||||
background: #1a1a1a;
|
||||
}
|
||||
.player-card.synced {
|
||||
border-color: #00a4dc;
|
||||
}
|
||||
.player-card.master {
|
||||
border-color: #52b54b;
|
||||
border-width: 2px;
|
||||
}
|
||||
.player-name {
|
||||
font-weight: bold;
|
||||
font-size: 1.1em;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.player-info {
|
||||
color: #888;
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.player-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.status-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.status-dot.on { background: #52b54b; }
|
||||
.status-dot.standby { background: #f9a825; }
|
||||
.status-dot.off { background: #f44336; }
|
||||
.sync-group {
|
||||
border: 2px dashed #00a4dc;
|
||||
border-radius: 12px;
|
||||
padding: 15px;
|
||||
margin-bottom: 20px;
|
||||
background: rgba(0, 164, 220, 0.05);
|
||||
}
|
||||
.sync-group-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
.sync-group-title {
|
||||
font-weight: bold;
|
||||
color: #00a4dc;
|
||||
}
|
||||
.sync-group-players {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.sync-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75em;
|
||||
margin-left: 8px;
|
||||
}
|
||||
.sync-badge.master {
|
||||
background: #52b54b;
|
||||
color: white;
|
||||
}
|
||||
.sync-badge.slave {
|
||||
background: #00a4dc;
|
||||
color: white;
|
||||
}
|
||||
.unsynced-section {
|
||||
margin-top: 30px;
|
||||
}
|
||||
.create-sync-section {
|
||||
margin-top: 30px;
|
||||
padding: 20px;
|
||||
border: 1px solid #444;
|
||||
border-radius: 8px;
|
||||
background: #1a1a1a;
|
||||
}
|
||||
.player-checkbox-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 15px;
|
||||
margin: 15px 0;
|
||||
}
|
||||
.player-checkbox-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
border: 1px solid #444;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.player-checkbox-item:hover {
|
||||
border-color: #00a4dc;
|
||||
}
|
||||
.player-checkbox-item.selected {
|
||||
border-color: #52b54b;
|
||||
background: rgba(82, 181, 75, 0.1);
|
||||
}
|
||||
.player-checkbox-item.master-selected {
|
||||
border-color: #52b54b;
|
||||
border-width: 2px;
|
||||
}
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.volume-slider {
|
||||
width: 100%;
|
||||
margin: 5px 0;
|
||||
}
|
||||
.help-text {
|
||||
color: #888;
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="JellyLmsSyncPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<h2>LMS Player Sync Management</h2>
|
||||
<p>Manage synchronized playback groups for your LMS players. Synced players will play audio in perfect sync.</p>
|
||||
|
||||
<div>
|
||||
<button is="emby-button" type="button" id="btnRefresh" class="raised button-alt emby-button">
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="syncGroupsSection" style="margin-top: 20px;">
|
||||
<h3>Current Sync Groups</h3>
|
||||
<div id="syncGroupsList">
|
||||
<p>Loading sync groups...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="unsyncedPlayersSection" class="unsynced-section">
|
||||
<h3>Available Players</h3>
|
||||
<div id="unsyncedPlayersList">
|
||||
<p>Loading players...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="create-sync-section">
|
||||
<h3>Create Sync Group</h3>
|
||||
<p class="help-text">Select players to sync together. The first selected player will be the master (controls playback).</p>
|
||||
|
||||
<div id="playerSelectionList" class="player-checkbox-list">
|
||||
<!-- Players will be populated here -->
|
||||
</div>
|
||||
|
||||
<div class="action-buttons">
|
||||
<button is="emby-button" type="button" id="btnCreateSync" class="raised button-submit emby-button" disabled>
|
||||
<span>Create Sync Group</span>
|
||||
</button>
|
||||
<button is="emby-button" type="button" id="btnClearSelection" class="raised button-alt emby-button">
|
||||
<span>Clear Selection</span>
|
||||
</button>
|
||||
</div>
|
||||
<div id="syncStatus" style="margin-top: 10px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
var JellyLmsSync = {
|
||||
pluginUniqueId: 'a5b8c9d0-1e2f-3a4b-5c6d-7e8f9a0b1c2d',
|
||||
players: [],
|
||||
syncGroups: [],
|
||||
selectedPlayers: []
|
||||
};
|
||||
|
||||
function getStatusClass(player) {
|
||||
if (!player.IsConnected) return 'off';
|
||||
return player.IsPoweredOn ? 'on' : 'standby';
|
||||
}
|
||||
|
||||
function getStatusText(player) {
|
||||
if (!player.IsConnected) return 'Disconnected';
|
||||
return player.IsPoweredOn ? 'On' : 'Standby';
|
||||
}
|
||||
|
||||
function loadData() {
|
||||
Promise.all([
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/Players', { refresh: true }),
|
||||
type: 'GET',
|
||||
dataType: 'json'
|
||||
}),
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups'),
|
||||
type: 'GET',
|
||||
dataType: 'json'
|
||||
})
|
||||
]).then(function(results) {
|
||||
JellyLmsSync.players = results[0] || [];
|
||||
JellyLmsSync.syncGroups = results[1] || [];
|
||||
renderSyncGroups();
|
||||
renderUnsyncedPlayers();
|
||||
renderPlayerSelection();
|
||||
}).catch(function(err) {
|
||||
console.error('Error loading data:', err);
|
||||
document.querySelector('#syncGroupsList').innerHTML = '<p style="color: red;">Error loading data. Check LMS connection.</p>';
|
||||
});
|
||||
}
|
||||
|
||||
function renderSyncGroups() {
|
||||
var container = document.querySelector('#syncGroupsList');
|
||||
var groups = JellyLmsSync.syncGroups;
|
||||
|
||||
if (!groups || groups.length === 0) {
|
||||
container.innerHTML = '<p>No sync groups configured. Create one below!</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
groups.forEach(function(group) {
|
||||
html += '<div class="sync-group">';
|
||||
html += '<div class="sync-group-header">';
|
||||
html += '<span class="sync-group-title">Sync Group (' + group.PlayerCount + ' players)</span>';
|
||||
html += '<button is="emby-button" type="button" class="raised button-alt emby-button btnDissolveGroup" data-master="' + group.MasterMac + '">';
|
||||
html += '<span>Dissolve Group</span>';
|
||||
html += '</button>';
|
||||
html += '</div>';
|
||||
html += '<div class="sync-group-players">';
|
||||
|
||||
// Master player
|
||||
var masterPlayer = JellyLmsSync.players.find(function(p) { return p.MacAddress === group.MasterMac; });
|
||||
if (masterPlayer) {
|
||||
html += renderPlayerCard(masterPlayer, true, false);
|
||||
}
|
||||
|
||||
// Slave players
|
||||
group.SlaveMacs.forEach(function(slaveMac, index) {
|
||||
var slavePlayer = JellyLmsSync.players.find(function(p) { return p.MacAddress === slaveMac; });
|
||||
if (slavePlayer) {
|
||||
html += renderPlayerCard(slavePlayer, false, true, group.SlaveNames[index]);
|
||||
}
|
||||
});
|
||||
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
|
||||
// Attach event listeners for dissolve buttons
|
||||
container.querySelectorAll('.btnDissolveGroup').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
dissolveGroup(this.getAttribute('data-master'));
|
||||
});
|
||||
});
|
||||
|
||||
// Attach event listeners for unsync buttons
|
||||
container.querySelectorAll('.btnUnsyncPlayer').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
unsyncPlayer(this.getAttribute('data-mac'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderPlayerCard(player, isMaster, isSlave, slaveName) {
|
||||
var statusClass = getStatusClass(player);
|
||||
var cardClass = 'player-card';
|
||||
if (isMaster) cardClass += ' master';
|
||||
else if (isSlave) cardClass += ' synced';
|
||||
|
||||
var html = '<div class="' + cardClass + '">';
|
||||
html += '<div class="player-name">' + player.Name;
|
||||
if (isMaster) html += '<span class="sync-badge master">Master</span>';
|
||||
else if (isSlave) html += '<span class="sync-badge slave">Synced</span>';
|
||||
html += '</div>';
|
||||
html += '<div class="player-info">' + player.Model + '</div>';
|
||||
html += '<div class="player-status">';
|
||||
html += '<span class="status-dot ' + statusClass + '"></span>';
|
||||
html += '<span>' + getStatusText(player) + '</span>';
|
||||
html += '<span style="margin-left: auto;">Vol: ' + player.Volume + '%</span>';
|
||||
html += '</div>';
|
||||
|
||||
if (isSlave) {
|
||||
html += '<button is="emby-button" type="button" class="raised button-alt emby-button btnUnsyncPlayer" data-mac="' + player.MacAddress + '" style="width: 100%; margin-top: 5px;">';
|
||||
html += '<span>Unsync</span>';
|
||||
html += '</button>';
|
||||
}
|
||||
|
||||
html += '</div>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function renderUnsyncedPlayers() {
|
||||
var container = document.querySelector('#unsyncedPlayersList');
|
||||
var syncedMacs = new Set();
|
||||
|
||||
JellyLmsSync.syncGroups.forEach(function(group) {
|
||||
syncedMacs.add(group.MasterMac);
|
||||
group.SlaveMacs.forEach(function(mac) { syncedMacs.add(mac); });
|
||||
});
|
||||
|
||||
var unsyncedPlayers = JellyLmsSync.players.filter(function(p) {
|
||||
return !syncedMacs.has(p.MacAddress);
|
||||
});
|
||||
|
||||
if (unsyncedPlayers.length === 0) {
|
||||
container.innerHTML = '<p>All players are in sync groups.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '<div class="sync-container">';
|
||||
unsyncedPlayers.forEach(function(player) {
|
||||
html += renderPlayerCard(player, false, false);
|
||||
});
|
||||
html += '</div>';
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderPlayerSelection() {
|
||||
var container = document.querySelector('#playerSelectionList');
|
||||
var players = JellyLmsSync.players;
|
||||
|
||||
if (!players || players.length === 0) {
|
||||
container.innerHTML = '<p>No players available.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Only show unsynced players for selection
|
||||
var syncedMacs = new Set();
|
||||
JellyLmsSync.syncGroups.forEach(function(group) {
|
||||
syncedMacs.add(group.MasterMac);
|
||||
group.SlaveMacs.forEach(function(mac) { syncedMacs.add(mac); });
|
||||
});
|
||||
|
||||
var availablePlayers = players.filter(function(p) {
|
||||
return !syncedMacs.has(p.MacAddress);
|
||||
});
|
||||
|
||||
if (availablePlayers.length < 2) {
|
||||
container.innerHTML = '<p>Need at least 2 unsynced players to create a sync group.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
var html = '';
|
||||
availablePlayers.forEach(function(player) {
|
||||
var isSelected = JellyLmsSync.selectedPlayers.indexOf(player.MacAddress) !== -1;
|
||||
var isMaster = JellyLmsSync.selectedPlayers.length > 0 && JellyLmsSync.selectedPlayers[0] === player.MacAddress;
|
||||
var statusClass = getStatusClass(player);
|
||||
|
||||
var itemClass = 'player-checkbox-item';
|
||||
if (isSelected) itemClass += ' selected';
|
||||
if (isMaster) itemClass += ' master-selected';
|
||||
|
||||
html += '<div class="' + itemClass + '" data-mac="' + player.MacAddress + '">';
|
||||
html += '<span class="status-dot ' + statusClass + '"></span>';
|
||||
html += '<span>' + player.Name + '</span>';
|
||||
if (isMaster) html += '<span class="sync-badge master">Master</span>';
|
||||
else if (isSelected) html += '<span class="sync-badge slave">Slave</span>';
|
||||
html += '</div>';
|
||||
});
|
||||
|
||||
container.innerHTML = html;
|
||||
|
||||
// Attach click listeners
|
||||
container.querySelectorAll('.player-checkbox-item').forEach(function(item) {
|
||||
item.addEventListener('click', function() {
|
||||
togglePlayerSelection(this.getAttribute('data-mac'));
|
||||
});
|
||||
});
|
||||
|
||||
updateCreateButton();
|
||||
}
|
||||
|
||||
function togglePlayerSelection(mac) {
|
||||
var index = JellyLmsSync.selectedPlayers.indexOf(mac);
|
||||
if (index === -1) {
|
||||
JellyLmsSync.selectedPlayers.push(mac);
|
||||
} else {
|
||||
JellyLmsSync.selectedPlayers.splice(index, 1);
|
||||
}
|
||||
renderPlayerSelection();
|
||||
}
|
||||
|
||||
function updateCreateButton() {
|
||||
var btn = document.querySelector('#btnCreateSync');
|
||||
btn.disabled = JellyLmsSync.selectedPlayers.length < 2;
|
||||
}
|
||||
|
||||
function createSyncGroup() {
|
||||
if (JellyLmsSync.selectedPlayers.length < 2) return;
|
||||
|
||||
var statusDiv = document.querySelector('#syncStatus');
|
||||
statusDiv.innerHTML = '<span style="color: orange;">Creating sync group...</span>';
|
||||
|
||||
var masterMac = JellyLmsSync.selectedPlayers[0];
|
||||
var slaveMacs = JellyLmsSync.selectedPlayers.slice(1);
|
||||
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups'),
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({
|
||||
MasterMac: masterMac,
|
||||
SlaveMacs: slaveMacs
|
||||
})
|
||||
}).then(function() {
|
||||
statusDiv.innerHTML = '<span style="color: green;">Sync group created successfully!</span>';
|
||||
JellyLmsSync.selectedPlayers = [];
|
||||
setTimeout(function() {
|
||||
statusDiv.innerHTML = '';
|
||||
loadData();
|
||||
}, 1500);
|
||||
}).catch(function(err) {
|
||||
statusDiv.innerHTML = '<span style="color: red;">Failed to create sync group.</span>';
|
||||
console.error('Error creating sync group:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function dissolveGroup(masterMac) {
|
||||
if (!confirm('Dissolve this sync group? All players will be unsynced.')) return;
|
||||
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups/' + encodeURIComponent(masterMac)),
|
||||
type: 'DELETE'
|
||||
}).then(function() {
|
||||
loadData();
|
||||
}).catch(function(err) {
|
||||
alert('Failed to dissolve sync group.');
|
||||
console.error('Error dissolving sync group:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function unsyncPlayer(mac) {
|
||||
ApiClient.ajax({
|
||||
url: ApiClient.getUrl('JellyLms/SyncGroups/Players/' + encodeURIComponent(mac)),
|
||||
type: 'DELETE'
|
||||
}).then(function() {
|
||||
loadData();
|
||||
}).catch(function(err) {
|
||||
alert('Failed to unsync player.');
|
||||
console.error('Error unsyncing player:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
JellyLmsSync.selectedPlayers = [];
|
||||
renderPlayerSelection();
|
||||
}
|
||||
|
||||
document.querySelector('#JellyLmsSyncPage')
|
||||
.addEventListener('pageshow', function() {
|
||||
loadData();
|
||||
});
|
||||
|
||||
document.querySelector('#btnRefresh')
|
||||
.addEventListener('click', function() {
|
||||
loadData();
|
||||
});
|
||||
|
||||
document.querySelector('#btnCreateSync')
|
||||
.addEventListener('click', function() {
|
||||
createSyncGroup();
|
||||
});
|
||||
|
||||
document.querySelector('#btnClearSelection')
|
||||
.addEventListener('click', function() {
|
||||
clearSelection();
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -27,9 +27,11 @@
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Configuration\configPage.html" />
|
||||
<None Remove="Configuration\syncPage.html" />
|
||||
<EmbeddedResource Include="Configuration\configPage.html" />
|
||||
<EmbeddedResource Include="Configuration\syncPage.html" />
|
||||
<None Remove="Web\RemoteControl.html" />
|
||||
<EmbeddedResource Include="Web\RemoteControl.html" />
|
||||
<None Remove="Web\remote-button.js" />
|
||||
<EmbeddedResource Include="Web\remote-button.js" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -9,9 +9,14 @@ namespace Jellyfin.Plugin.JellyLMS.Models;
|
||||
public enum PlaybackState
|
||||
{
|
||||
/// <summary>
|
||||
/// Playback is stopped.
|
||||
/// Device connected, no media loaded.
|
||||
/// </summary>
|
||||
Stopped,
|
||||
Idle,
|
||||
|
||||
/// <summary>
|
||||
/// Play command sent, waiting for LMS to confirm playback started.
|
||||
/// </summary>
|
||||
Loading,
|
||||
|
||||
/// <summary>
|
||||
/// Playback is active.
|
||||
@@ -21,7 +26,84 @@ public enum PlaybackState
|
||||
/// <summary>
|
||||
/// Playback is paused.
|
||||
/// </summary>
|
||||
Paused
|
||||
Paused,
|
||||
|
||||
/// <summary>
|
||||
/// Position change in progress.
|
||||
/// </summary>
|
||||
Seeking,
|
||||
|
||||
/// <summary>
|
||||
/// Playback failed with an error.
|
||||
/// </summary>
|
||||
Error,
|
||||
|
||||
/// <summary>
|
||||
/// Playback has ended.
|
||||
/// </summary>
|
||||
Stopped
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Types of playback errors.
|
||||
/// </summary>
|
||||
public enum PlaybackErrorType
|
||||
{
|
||||
/// <summary>
|
||||
/// No error.
|
||||
/// </summary>
|
||||
None,
|
||||
|
||||
/// <summary>
|
||||
/// Operation timed out waiting for LMS response.
|
||||
/// </summary>
|
||||
Timeout,
|
||||
|
||||
/// <summary>
|
||||
/// Network error communicating with LMS.
|
||||
/// </summary>
|
||||
NetworkError,
|
||||
|
||||
/// <summary>
|
||||
/// LMS returned an error.
|
||||
/// </summary>
|
||||
LmsError,
|
||||
|
||||
/// <summary>
|
||||
/// Error with the audio stream from Jellyfin.
|
||||
/// </summary>
|
||||
StreamError,
|
||||
|
||||
/// <summary>
|
||||
/// Unknown error.
|
||||
/// </summary>
|
||||
Unknown
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Contains details about a playback error.
|
||||
/// </summary>
|
||||
public class PlaybackErrorInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the type of error.
|
||||
/// </summary>
|
||||
public PlaybackErrorType ErrorType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error message.
|
||||
/// </summary>
|
||||
public string Message { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets when the error occurred.
|
||||
/// </summary>
|
||||
public DateTime OccurredAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of retry attempts made.
|
||||
/// </summary>
|
||||
public int RetryCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,7 +149,12 @@ public class LmsPlaybackSession
|
||||
/// <summary>
|
||||
/// Gets or sets the current playback state.
|
||||
/// </summary>
|
||||
public PlaybackState State { get; set; } = PlaybackState.Stopped;
|
||||
public PlaybackState State { get; set; } = PlaybackState.Idle;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the last error that occurred during playback.
|
||||
/// </summary>
|
||||
public PlaybackErrorInfo? LastError { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current playback position in ticks.
|
||||
|
||||
@@ -2,10 +2,12 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Jellyfin.Plugin.JellyLMS.Configuration;
|
||||
using Jellyfin.Plugin.JellyLMS.Services;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Plugins;
|
||||
using MediaBrowser.Model.Plugins;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.JellyLMS;
|
||||
|
||||
@@ -15,15 +17,22 @@ namespace Jellyfin.Plugin.JellyLMS;
|
||||
/// </summary>
|
||||
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
{
|
||||
private readonly ILogger<Plugin> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Plugin"/> class.
|
||||
/// </summary>
|
||||
/// <param name="applicationPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
|
||||
/// <param name="xmlSerializer">Instance of the <see cref="IXmlSerializer"/> interface.</param>
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
|
||||
/// <param name="logger">The logger.</param>
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, ILogger<Plugin> logger)
|
||||
: base(applicationPaths, xmlSerializer)
|
||||
{
|
||||
Instance = this;
|
||||
_logger = logger;
|
||||
|
||||
WebClientPatchService.Apply(ApplicationPaths, Configuration.EnableHomeScreenButton, _logger);
|
||||
ConfigurationChanged += (_, _) => WebClientPatchService.Apply(ApplicationPaths, Configuration.EnableHomeScreenButton, _logger);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -49,11 +58,6 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
{
|
||||
Name = Name,
|
||||
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Configuration.configPage.html", GetType().Namespace)
|
||||
},
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = "JellyLMS Sync",
|
||||
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Configuration.syncPage.html", GetType().Namespace)
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
@@ -15,8 +15,6 @@ public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||
{
|
||||
serviceCollection.AddSingleton<ILmsApiClient, LmsApiClient>();
|
||||
serviceCollection.AddSingleton<LmsPlayerManager>();
|
||||
serviceCollection.AddSingleton<LmsSessionManager>();
|
||||
serviceCollection.AddHostedService(sp => sp.GetRequiredService<LmsSessionManager>());
|
||||
|
||||
// Device discovery service - registers LMS players as Jellyfin sessions for casting
|
||||
// Use AddHostedService directly to let DI handle construction
|
||||
|
||||
@@ -226,8 +226,10 @@ public class LmsApiClient : ILmsApiClient, IDisposable
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("LMS SeekAsync: player {Mac}, position {Seconds}s", playerMac, positionSeconds);
|
||||
await SendCommandAsync<object>(playerMac, ["time", positionSeconds.ToString("F1", CultureInfo.InvariantCulture)])
|
||||
.ConfigureAwait(false);
|
||||
_logger.LogInformation("LMS SeekAsync: command sent successfully");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.JellyLMS.Configuration;
|
||||
using Jellyfin.Plugin.JellyLMS.Models;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
@@ -23,9 +23,16 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
private readonly SessionInfo _session;
|
||||
private readonly ISessionManager _sessionManager;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly PlaybackStateMachine _stateMachine;
|
||||
private readonly LmsStatusPoller _statusPoller;
|
||||
private readonly CancellationTokenSource _cancellationTokenSource = new();
|
||||
private Timer? _progressTimer;
|
||||
private bool _disposed;
|
||||
private BaseItem? _currentItem;
|
||||
private Guid[] _playlist = [];
|
||||
private int _playlistIndex;
|
||||
private long _seekOffsetTicks; // Offset from transcoded stream start position
|
||||
private PlaybackErrorInfo? _lastError;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LmsSessionController"/> class.
|
||||
@@ -50,22 +57,41 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
_session = session;
|
||||
_sessionManager = sessionManager;
|
||||
_libraryManager = libraryManager;
|
||||
_stateMachine = new PlaybackStateMachine(logger);
|
||||
_statusPoller = new LmsStatusPoller(lmsClient, logger);
|
||||
|
||||
// Start status polling immediately to keep volume in sync
|
||||
StartProgressTimer();
|
||||
}
|
||||
|
||||
private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the currently playing item ID.
|
||||
/// </summary>
|
||||
public Guid? CurrentItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether playback is currently active.
|
||||
/// Gets a value indicating whether playback is currently active.
|
||||
/// </summary>
|
||||
public bool IsPlaying { get; set; }
|
||||
public bool IsPlaying => _stateMachine.CurrentState == PlaybackState.Playing
|
||||
|| _stateMachine.CurrentState == PlaybackState.Loading
|
||||
|| _stateMachine.CurrentState == PlaybackState.Seeking;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether playback is paused.
|
||||
/// Gets a value indicating whether playback is paused.
|
||||
/// </summary>
|
||||
public bool IsPaused { get; set; }
|
||||
public bool IsPaused => _stateMachine.CurrentState == PlaybackState.Paused;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current playback state.
|
||||
/// </summary>
|
||||
public PlaybackState State => _stateMachine.CurrentState;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last error that occurred during playback.
|
||||
/// </summary>
|
||||
public PlaybackErrorInfo? LastError => _lastError;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsSessionActive => _player.IsConnected;
|
||||
@@ -86,10 +112,20 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"LMS Session Controller received message {MessageType} for player {PlayerName} ({Mac})",
|
||||
"LMS Session Controller received message {MessageType} for player {PlayerName} ({Mac}), data type: {DataType}",
|
||||
name,
|
||||
_player.Name,
|
||||
_player.MacAddress);
|
||||
_player.MacAddress,
|
||||
data?.GetType().Name ?? "null");
|
||||
|
||||
// Log the data for debugging
|
||||
if (data is PlaystateRequest psr)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"PlaystateRequest: Command={Command}, SeekPositionTicks={Ticks}",
|
||||
psr.Command,
|
||||
psr.SeekPositionTicks);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
@@ -137,41 +173,99 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
await _lmsClient.PowerOnAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// For now, play the first item
|
||||
// TODO: Support playlists/queues
|
||||
if (playRequest.ItemIds.Length > 0)
|
||||
{
|
||||
var itemId = playRequest.ItemIds[0];
|
||||
var streamUrl = BuildStreamUrl(itemId);
|
||||
// Store the full playlist
|
||||
_playlist = playRequest.ItemIds;
|
||||
_playlistIndex = playRequest.StartIndex ?? 0;
|
||||
|
||||
_logger.LogInformation("Playing stream URL: {Url}", streamUrl);
|
||||
await _lmsClient.PlayUrlAsync(_player.MacAddress, streamUrl).ConfigureAwait(false);
|
||||
|
||||
// Track current playback state
|
||||
CurrentItemId = itemId;
|
||||
IsPlaying = true;
|
||||
IsPaused = false;
|
||||
|
||||
// Look up the item for duration info
|
||||
_currentItem = _libraryManager.GetItemById(itemId);
|
||||
|
||||
// Seek to start position if specified
|
||||
var startPositionTicks = 0L;
|
||||
if (playRequest.StartPositionTicks.HasValue && playRequest.StartPositionTicks.Value > 0)
|
||||
{
|
||||
startPositionTicks = playRequest.StartPositionTicks.Value;
|
||||
var positionSeconds = startPositionTicks / TimeSpan.TicksPerSecond;
|
||||
await _lmsClient.SeekAsync(_player.MacAddress, positionSeconds).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Report playback start to Jellyfin
|
||||
await ReportPlaybackStartAsync(itemId, startPositionTicks).ConfigureAwait(false);
|
||||
|
||||
// Start progress reporting timer (every 2 seconds)
|
||||
StartProgressTimer();
|
||||
// Play the item at the start index
|
||||
await PlayItemAtIndexAsync(_playlistIndex, playRequest.StartPositionTicks ?? 0).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PlayItemAtIndexAsync(int index, long startPositionTicks = 0)
|
||||
{
|
||||
if (index < 0 || index >= _playlist.Length)
|
||||
{
|
||||
_logger.LogWarning("Invalid playlist index {Index}, playlist has {Count} items", index, _playlist.Length);
|
||||
return;
|
||||
}
|
||||
|
||||
var itemId = _playlist[index];
|
||||
_playlistIndex = index;
|
||||
|
||||
// Look up the item first - we need it for file path if using direct mode
|
||||
_currentItem = _libraryManager.GetItemById(itemId);
|
||||
|
||||
// Build stream URL/path with start position
|
||||
var (streamUrl, useDirectPath) = BuildPlaybackUrl(itemId, startPositionTicks);
|
||||
_logger.LogInformation(
|
||||
"Playing item {Index}/{Total} from position {Position}s (direct={Direct}): {Url}",
|
||||
index + 1,
|
||||
_playlist.Length,
|
||||
startPositionTicks / TimeSpan.TicksPerSecond,
|
||||
useDirectPath,
|
||||
streamUrl);
|
||||
|
||||
// Transition to Loading state before sending command
|
||||
_stateMachine.TryTransition(PlaybackState.Loading, "Starting playback");
|
||||
|
||||
// Send play command with retry logic
|
||||
var playSuccess = await _statusPoller.ExecuteWithRetryAsync(
|
||||
async () => await _lmsClient.PlayUrlAsync(_player.MacAddress, streamUrl).ConfigureAwait(false),
|
||||
Config.MaxAutoRetries,
|
||||
retry => _logger.LogInformation("Retrying play command (attempt {Retry})", retry),
|
||||
_cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
if (!playSuccess)
|
||||
{
|
||||
_lastError = new PlaybackErrorInfo
|
||||
{
|
||||
ErrorType = PlaybackErrorType.LmsError,
|
||||
Message = "Failed to send play command to LMS after retries",
|
||||
OccurredAt = DateTime.UtcNow,
|
||||
RetryCount = Config.MaxAutoRetries
|
||||
};
|
||||
_stateMachine.TryTransition(PlaybackState.Error, "Play command failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for LMS to confirm playback started
|
||||
var loadingTimeout = TimeSpan.FromSeconds(Config.LoadingTimeoutSeconds);
|
||||
var started = await _statusPoller.WaitForPlaybackStartAsync(
|
||||
_player.MacAddress,
|
||||
loadingTimeout,
|
||||
_cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
if (!started)
|
||||
{
|
||||
_lastError = new PlaybackErrorInfo
|
||||
{
|
||||
ErrorType = PlaybackErrorType.Timeout,
|
||||
Message = $"LMS did not start playing within {loadingTimeout.TotalSeconds}s",
|
||||
OccurredAt = DateTime.UtcNow
|
||||
};
|
||||
_stateMachine.TryTransition(PlaybackState.Error, "Loading timeout");
|
||||
return;
|
||||
}
|
||||
|
||||
// Track current playback state
|
||||
CurrentItemId = itemId;
|
||||
_stateMachine.TryTransition(PlaybackState.Playing, "LMS confirmed playback");
|
||||
|
||||
// Track the seek offset so we report the correct position
|
||||
// When using direct file paths, LMS handles seeking natively so no offset needed
|
||||
// When using HTTP streaming with startTimeTicks, the stream starts at 0 but we need to report actual position
|
||||
_seekOffsetTicks = useDirectPath ? 0 : startPositionTicks;
|
||||
|
||||
// Report playback start to Jellyfin
|
||||
await ReportPlaybackStartAsync(itemId, startPositionTicks).ConfigureAwait(false);
|
||||
|
||||
// Start progress reporting timer (every 2 seconds)
|
||||
StartProgressTimer();
|
||||
}
|
||||
|
||||
private async Task ReportPlaybackStartAsync(Guid itemId, long positionTicks)
|
||||
{
|
||||
try
|
||||
@@ -204,7 +298,7 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
// Stop any existing timer
|
||||
_progressTimer?.Dispose();
|
||||
|
||||
// Report progress every 2 seconds
|
||||
// Poll status every 2 seconds (for progress reporting when playing and volume sync always)
|
||||
_progressTimer = new Timer(
|
||||
async _ => await ReportPlaybackProgressAsync().ConfigureAwait(false),
|
||||
null,
|
||||
@@ -214,36 +308,86 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
|
||||
private void StopProgressTimer()
|
||||
{
|
||||
_progressTimer?.Dispose();
|
||||
_progressTimer = null;
|
||||
// Don't actually stop the timer - keep polling for volume updates
|
||||
// This ensures Jellyfin stays in sync with the device volume
|
||||
// even when not playing media
|
||||
}
|
||||
|
||||
private async Task ReportPlaybackProgressAsync()
|
||||
{
|
||||
if (!IsPlaying || !CurrentItemId.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Always poll status to keep volume in sync, even when not playing
|
||||
var status = await _lmsClient.GetPlayerStatusAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
if (status == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var positionTicks = (long)(status.Time * TimeSpan.TicksPerSecond);
|
||||
var isPaused = status.Mode == "pause";
|
||||
// Update cached volume so Jellyfin stays in sync with device
|
||||
_player.Volume = status.Volume;
|
||||
|
||||
// Update our local state from LMS
|
||||
IsPaused = isPaused;
|
||||
|
||||
// Check if playback has stopped on LMS side
|
||||
if (status.Mode == "stop")
|
||||
// Don't report playback progress during Loading, Seeking, Error, Stopped, or Idle states
|
||||
var currentState = _stateMachine.CurrentState;
|
||||
if (currentState == PlaybackState.Loading
|
||||
|| currentState == PlaybackState.Seeking
|
||||
|| currentState == PlaybackState.Error
|
||||
|| currentState == PlaybackState.Stopped
|
||||
|| currentState == PlaybackState.Idle
|
||||
|| !CurrentItemId.HasValue)
|
||||
{
|
||||
_logger.LogInformation("LMS playback stopped, reporting to Jellyfin");
|
||||
await ReportPlaybackStoppedAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// LMS reports time relative to the current stream, but after seeking
|
||||
// we're playing a transcoded stream that starts at the seek position.
|
||||
// Add the seek offset to get the actual track position.
|
||||
var positionTicks = (long)(status.Time * TimeSpan.TicksPerSecond) + _seekOffsetTicks;
|
||||
var lmsIsPaused = status.Mode == "pause";
|
||||
|
||||
// Sync state machine with LMS state (handles external pause/play)
|
||||
if (lmsIsPaused && currentState == PlaybackState.Playing)
|
||||
{
|
||||
_stateMachine.TryTransition(PlaybackState.Paused, "LMS reported pause");
|
||||
}
|
||||
else if (!lmsIsPaused && status.Mode == "play" && currentState == PlaybackState.Paused)
|
||||
{
|
||||
_stateMachine.TryTransition(PlaybackState.Playing, "LMS reported play");
|
||||
}
|
||||
|
||||
// Check if playback has stopped on LMS side (track ended)
|
||||
if (status.Mode == "stop" && currentState == PlaybackState.Playing)
|
||||
{
|
||||
// Confirm stop with a quick poll instead of fixed delay
|
||||
var stillStopped = await _statusPoller.WaitForModeAsync(
|
||||
_player.MacAddress,
|
||||
"stop",
|
||||
TimeSpan.FromMilliseconds(500),
|
||||
_cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
if (!stillStopped)
|
||||
{
|
||||
_logger.LogDebug("LMS mode changed from stop, ignoring");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("LMS playback stopped, checking if we should advance to next track");
|
||||
|
||||
// Check if there are more tracks in the playlist
|
||||
if (_playlistIndex < _playlist.Length - 1)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Track ended, advancing to next track (index {Index}/{Total})",
|
||||
_playlistIndex + 2,
|
||||
_playlist.Length);
|
||||
await PlayItemAtIndexAsync(_playlistIndex + 1).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Playlist finished, reporting playback stopped");
|
||||
await ReportPlaybackStoppedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -251,7 +395,7 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
{
|
||||
ItemId = CurrentItemId.Value,
|
||||
SessionId = _session.Id,
|
||||
IsPaused = isPaused,
|
||||
IsPaused = _stateMachine.CurrentState == PlaybackState.Paused,
|
||||
PositionTicks = positionTicks,
|
||||
PlayMethod = PlayMethod.DirectStream,
|
||||
CanSeek = true,
|
||||
@@ -287,8 +431,7 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
_logger.LogInformation("Reporting playback stopped for item {ItemId}", CurrentItemId.Value);
|
||||
await _sessionManager.OnPlaybackStopped(stopInfo).ConfigureAwait(false);
|
||||
|
||||
IsPlaying = false;
|
||||
IsPaused = false;
|
||||
_stateMachine.TryTransition(PlaybackState.Stopped, "Playback stopped");
|
||||
CurrentItemId = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -322,50 +465,155 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
case PlaystateCommand.Pause:
|
||||
var pauseResult = await _lmsClient.PauseAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
_logger.LogInformation("Pause command result: {Result}", pauseResult);
|
||||
IsPaused = true;
|
||||
_stateMachine.TryTransition(PlaybackState.Paused, "Pause command");
|
||||
break;
|
||||
|
||||
case PlaystateCommand.Unpause:
|
||||
var playResult = await _lmsClient.PlayAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
_logger.LogInformation("Unpause/Play command result: {Result}", playResult);
|
||||
IsPaused = false;
|
||||
_stateMachine.TryTransition(PlaybackState.Playing, "Unpause command");
|
||||
break;
|
||||
|
||||
case PlaystateCommand.PlayPause:
|
||||
// Toggle play/pause - check current state first
|
||||
var currentState = await _lmsClient.GetPlayerStatusAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
if (currentState?.Mode == "play")
|
||||
// Toggle play/pause based on current state
|
||||
if (_stateMachine.CurrentState == PlaybackState.Playing)
|
||||
{
|
||||
var togglePauseResult = await _lmsClient.PauseAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
_logger.LogInformation("PlayPause toggle (pause) result: {Result}", togglePauseResult);
|
||||
IsPaused = true;
|
||||
_stateMachine.TryTransition(PlaybackState.Paused, "PlayPause toggle to pause");
|
||||
}
|
||||
else
|
||||
{
|
||||
var togglePlayResult = await _lmsClient.PlayAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
_logger.LogInformation("PlayPause toggle (play) result: {Result}", togglePlayResult);
|
||||
IsPaused = false;
|
||||
_stateMachine.TryTransition(PlaybackState.Playing, "PlayPause toggle to play");
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case PlaystateCommand.Seek:
|
||||
if (playstateRequest.SeekPositionTicks.HasValue)
|
||||
_logger.LogInformation(
|
||||
"Seek command received for player {PlayerName}, SeekPositionTicks: {Ticks}, CurrentItemId: {ItemId}, CurrentSeekOffset: {Offset}",
|
||||
_player.Name,
|
||||
playstateRequest.SeekPositionTicks,
|
||||
CurrentItemId,
|
||||
_seekOffsetTicks);
|
||||
if (playstateRequest.SeekPositionTicks.HasValue && CurrentItemId.HasValue)
|
||||
{
|
||||
var positionSeconds = playstateRequest.SeekPositionTicks.Value / TimeSpan.TicksPerSecond;
|
||||
_logger.LogInformation(
|
||||
"Seeking player {PlayerName} to {Seconds} seconds",
|
||||
_player.Name,
|
||||
positionSeconds);
|
||||
await _lmsClient.SeekAsync(_player.MacAddress, positionSeconds).ConfigureAwait(false);
|
||||
var positionTicks = playstateRequest.SeekPositionTicks.Value;
|
||||
var positionSeconds = (double)(positionTicks / TimeSpan.TicksPerSecond);
|
||||
|
||||
// Transition to Seeking state (state machine remembers previous state)
|
||||
_stateMachine.TryTransition(PlaybackState.Seeking, "Seek command");
|
||||
|
||||
// Check if we're using direct file path mode - if so, LMS can seek natively
|
||||
if (CanSeekNatively())
|
||||
{
|
||||
// Use native LMS seeking - much smoother!
|
||||
_logger.LogInformation("Seeking natively to {Seconds}s using LMS time command", positionSeconds);
|
||||
await _lmsClient.SeekAsync(_player.MacAddress, positionSeconds).ConfigureAwait(false);
|
||||
|
||||
// Wait for seek to complete
|
||||
var seekTimeout = TimeSpan.FromSeconds(Config.SeekTimeoutSeconds);
|
||||
var seekComplete = await _statusPoller.WaitForSeekCompleteAsync(
|
||||
_player.MacAddress,
|
||||
positionSeconds,
|
||||
toleranceSeconds: 2.0,
|
||||
seekTimeout,
|
||||
_cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
// No seek offset needed - LMS handles position tracking natively
|
||||
_seekOffsetTicks = 0;
|
||||
|
||||
// Restore previous state
|
||||
var previousState = _stateMachine.StateBeforeSeek;
|
||||
if (seekComplete)
|
||||
{
|
||||
_stateMachine.TryTransition(previousState, "Seek completed");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Seek may not have completed within timeout, restoring state anyway");
|
||||
_stateMachine.TryTransition(previousState, "Seek timeout - restoring state");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// For HTTP streams, LMS can't seek directly - we need to restart with startTimeTicks
|
||||
// This is essentially a new playback, so transition to Loading
|
||||
_stateMachine.TryTransition(PlaybackState.Loading, "HTTP stream seek - restarting");
|
||||
|
||||
var streamUrl = BuildStreamUrlWithPosition(CurrentItemId.Value, positionTicks);
|
||||
_logger.LogInformation(
|
||||
"Seeking by restarting stream at position {Seconds}s: {Url}",
|
||||
positionSeconds,
|
||||
streamUrl);
|
||||
|
||||
await _lmsClient.PlayUrlAsync(_player.MacAddress, streamUrl).ConfigureAwait(false);
|
||||
|
||||
// Wait for playback to start
|
||||
var loadingTimeout = TimeSpan.FromSeconds(Config.LoadingTimeoutSeconds);
|
||||
var started = await _statusPoller.WaitForPlaybackStartAsync(
|
||||
_player.MacAddress,
|
||||
loadingTimeout,
|
||||
_cancellationTokenSource.Token).ConfigureAwait(false);
|
||||
|
||||
// Track the seek offset so we report the correct position
|
||||
_seekOffsetTicks = positionTicks;
|
||||
|
||||
if (started)
|
||||
{
|
||||
_stateMachine.TryTransition(PlaybackState.Playing, "HTTP stream seek completed");
|
||||
}
|
||||
else
|
||||
{
|
||||
_lastError = new PlaybackErrorInfo
|
||||
{
|
||||
ErrorType = PlaybackErrorType.Timeout,
|
||||
Message = "Stream restart after seek failed to start",
|
||||
OccurredAt = DateTime.UtcNow
|
||||
};
|
||||
_stateMachine.TryTransition(PlaybackState.Error, "HTTP stream seek failed");
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Seek offset is now {Ticks} ticks ({Seconds}s)", _seekOffsetTicks, _seekOffsetTicks / TimeSpan.TicksPerSecond);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Seek command received but SeekPositionTicks or CurrentItemId is null");
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case PlaystateCommand.NextTrack:
|
||||
if (_playlistIndex < _playlist.Length - 1)
|
||||
{
|
||||
_logger.LogInformation("Skipping to next track (index {Index})", _playlistIndex + 1);
|
||||
await PlayItemAtIndexAsync(_playlistIndex + 1).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Already at last track, stopping playback");
|
||||
await _lmsClient.StopAsync(_player.MacAddress).ConfigureAwait(false);
|
||||
await ReportPlaybackStoppedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case PlaystateCommand.PreviousTrack:
|
||||
// TODO: Implement playlist navigation
|
||||
_logger.LogDebug("Track navigation not yet implemented");
|
||||
if (_playlistIndex > 0)
|
||||
{
|
||||
_logger.LogInformation("Skipping to previous track (index {Index})", _playlistIndex - 1);
|
||||
await PlayItemAtIndexAsync(_playlistIndex - 1).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
// At first track, restart from beginning
|
||||
_logger.LogInformation("At first track, restarting from beginning");
|
||||
await _lmsClient.SeekAsync(_player.MacAddress, 0).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -432,15 +680,113 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the playback URL or file path for the given item.
|
||||
/// Returns a tuple of (url/path, isDirectFilePath).
|
||||
/// </summary>
|
||||
private (string Url, bool IsDirectPath) BuildPlaybackUrl(Guid itemId, long startPositionTicks)
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
|
||||
// Check if direct file path mode is enabled
|
||||
if (config?.UseDirectFilePath == true && _currentItem?.Path != null)
|
||||
{
|
||||
// Try each path mapping until one matches
|
||||
foreach (var mapping in config.GetAllPathMappings())
|
||||
{
|
||||
var directPath = BuildDirectFilePath(_currentItem.Path, mapping.JellyfinPath, mapping.LmsPath);
|
||||
if (directPath != null)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Using direct file path with mapping '{JellyfinPath}' -> '{LmsPath}': {OriginalPath} -> {MappedPath}",
|
||||
mapping.JellyfinPath,
|
||||
mapping.LmsPath,
|
||||
_currentItem.Path,
|
||||
directPath);
|
||||
return (directPath, true);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogWarning(
|
||||
"Direct file path mode enabled but no path mapping matched for: {Path}",
|
||||
_currentItem.Path);
|
||||
}
|
||||
|
||||
// Fall back to HTTP streaming
|
||||
return (BuildStreamUrlWithPosition(itemId, startPositionTicks), false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the current item can use native LMS seeking (direct file path mode).
|
||||
/// </summary>
|
||||
private bool CanSeekNatively()
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config?.UseDirectFilePath != true || _currentItem?.Path == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if any mapping matches the current item's path
|
||||
foreach (var mapping in config.GetAllPathMappings())
|
||||
{
|
||||
var normalizedPath = _currentItem.Path.Replace('\\', '/');
|
||||
var normalizedPrefix = mapping.JellyfinPath.TrimEnd('/', '\\').Replace('\\', '/');
|
||||
if (normalizedPath.StartsWith(normalizedPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps a Jellyfin file path to an LMS file path using the configured path prefixes.
|
||||
/// </summary>
|
||||
private static string? BuildDirectFilePath(string jellyfinPath, string jellyfinPrefix, string lmsPrefix)
|
||||
{
|
||||
// Normalize path separators for comparison
|
||||
var normalizedPath = jellyfinPath.Replace('\\', '/');
|
||||
var normalizedJellyfinPrefix = jellyfinPrefix.TrimEnd('/', '\\').Replace('\\', '/');
|
||||
var normalizedLmsPrefix = lmsPrefix.TrimEnd('/', '\\').Replace('\\', '/');
|
||||
|
||||
if (!normalizedPath.StartsWith(normalizedJellyfinPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Replace the prefix
|
||||
var relativePath = normalizedPath[normalizedJellyfinPrefix.Length..];
|
||||
return normalizedLmsPrefix + relativePath;
|
||||
}
|
||||
|
||||
private string BuildStreamUrl(Guid itemId)
|
||||
{
|
||||
return BuildStreamUrlWithPosition(itemId, 0);
|
||||
}
|
||||
|
||||
private string BuildStreamUrlWithPosition(Guid itemId, long startPositionTicks)
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
var jellyfinUrl = config?.JellyfinServerUrl?.TrimEnd('/') ?? "http://localhost:8096";
|
||||
var apiKey = config?.JellyfinApiKey ?? string.Empty;
|
||||
|
||||
// Build audio stream URL that LMS can fetch
|
||||
// Use direct stream endpoint - simpler and more compatible
|
||||
var url = $"{jellyfinUrl}/Audio/{itemId}/stream?static=true";
|
||||
string url;
|
||||
|
||||
if (startPositionTicks > 0)
|
||||
{
|
||||
// For seeking, we need to use transcoding (static=true doesn't support startTimeTicks)
|
||||
// Use MP3 transcoding with the start position
|
||||
// Add a cache-busting parameter to ensure we get a fresh stream on each seek
|
||||
var cacheBuster = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
url = $"{jellyfinUrl}/Audio/{itemId}/stream.mp3?audioCodec=mp3&audioBitRate=320000&startTimeTicks={startPositionTicks}&_={cacheBuster}";
|
||||
}
|
||||
else
|
||||
{
|
||||
// For normal playback from start, use static streaming (better quality, no transcoding)
|
||||
url = $"{jellyfinUrl}/Audio/{itemId}/stream.mp3?static=true";
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(apiKey))
|
||||
{
|
||||
@@ -470,7 +816,16 @@ public class LmsSessionController : ISessionController, IDisposable
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
StopProgressTimer();
|
||||
// Cancel any pending operations
|
||||
_cancellationTokenSource.Cancel();
|
||||
_cancellationTokenSource.Dispose();
|
||||
|
||||
// Actually stop the timer when disposing
|
||||
_progressTimer?.Dispose();
|
||||
_progressTimer = null;
|
||||
|
||||
// Reset state machine
|
||||
_stateMachine.Reset();
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
@@ -1,313 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.JellyLMS.Configuration;
|
||||
using Jellyfin.Plugin.JellyLMS.Models;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.JellyLMS.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Manages active playback sessions between Jellyfin and LMS.
|
||||
/// </summary>
|
||||
public class LmsSessionManager : IHostedService
|
||||
{
|
||||
private readonly ILogger<LmsSessionManager> _logger;
|
||||
private readonly ILmsApiClient _lmsClient;
|
||||
private readonly LmsPlayerManager _playerManager;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly ConcurrentDictionary<string, LmsPlaybackSession> _sessions = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LmsSessionManager"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">The logger instance.</param>
|
||||
/// <param name="lmsClient">The LMS API client.</param>
|
||||
/// <param name="playerManager">The player manager.</param>
|
||||
/// <param name="libraryManager">The Jellyfin library manager.</param>
|
||||
public LmsSessionManager(
|
||||
ILogger<LmsSessionManager> logger,
|
||||
ILmsApiClient lmsClient,
|
||||
LmsPlayerManager playerManager,
|
||||
ILibraryManager libraryManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_lmsClient = lmsClient;
|
||||
_playerManager = playerManager;
|
||||
_libraryManager = libraryManager;
|
||||
}
|
||||
|
||||
private PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
|
||||
/// <summary>
|
||||
/// Gets all active sessions.
|
||||
/// </summary>
|
||||
/// <returns>List of active sessions.</returns>
|
||||
public List<LmsPlaybackSession> GetActiveSessions()
|
||||
{
|
||||
return _sessions.Values.Where(s => s.State != PlaybackState.Stopped).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a session by ID.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>The session, or null if not found.</returns>
|
||||
public LmsPlaybackSession? GetSession(string sessionId)
|
||||
{
|
||||
return _sessions.GetValueOrDefault(sessionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts playback of a Jellyfin item on LMS players.
|
||||
/// </summary>
|
||||
/// <param name="itemId">The Jellyfin item ID.</param>
|
||||
/// <param name="playerMacs">The LMS player MAC addresses.</param>
|
||||
/// <param name="userId">Optional user ID.</param>
|
||||
/// <returns>The created session.</returns>
|
||||
public async Task<LmsPlaybackSession?> StartPlaybackAsync(
|
||||
Guid itemId,
|
||||
IEnumerable<string> playerMacs,
|
||||
Guid? userId = null)
|
||||
{
|
||||
var macList = playerMacs.ToList();
|
||||
if (macList.Count == 0)
|
||||
{
|
||||
_logger.LogWarning("No players specified for playback");
|
||||
return null;
|
||||
}
|
||||
|
||||
var item = _libraryManager.GetItemById(itemId);
|
||||
if (item == null)
|
||||
{
|
||||
_logger.LogWarning("Item {ItemId} not found", itemId);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Build the audio stream URL
|
||||
var streamUrl = BuildStreamUrl(itemId);
|
||||
|
||||
var session = new LmsPlaybackSession
|
||||
{
|
||||
ItemId = itemId,
|
||||
ItemName = item.Name,
|
||||
PlayerMacs = macList,
|
||||
State = PlaybackState.Playing,
|
||||
StreamUrl = streamUrl,
|
||||
UserId = userId,
|
||||
RuntimeTicks = item.RunTimeTicks ?? 0
|
||||
};
|
||||
|
||||
// If multiple players, sync them first
|
||||
if (macList.Count > 1)
|
||||
{
|
||||
var masterMac = macList[0];
|
||||
var slaveMacs = macList.Skip(1);
|
||||
await _playerManager.CreateSyncGroupAsync(masterMac, slaveMacs).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Start playback on the first player (others will sync)
|
||||
var targetMac = macList[0];
|
||||
var success = await _lmsClient.PlayUrlAsync(targetMac, streamUrl, item.Name).ConfigureAwait(false);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
_logger.LogError("Failed to start playback on player {Mac}", targetMac);
|
||||
return null;
|
||||
}
|
||||
|
||||
_sessions[session.SessionId] = session;
|
||||
_logger.LogInformation(
|
||||
"Started playback session {SessionId} for {Item} on {Count} players",
|
||||
session.SessionId,
|
||||
item.Name,
|
||||
macList.Count);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pauses a playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>True if successful.</returns>
|
||||
public async Task<bool> PauseSessionAsync(string sessionId)
|
||||
{
|
||||
if (!_sessions.TryGetValue(sessionId, out var session))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pause the master player (synced players will follow)
|
||||
var success = await _lmsClient.PauseAsync(session.PlayerMacs[0]).ConfigureAwait(false);
|
||||
|
||||
if (success)
|
||||
{
|
||||
session.State = PlaybackState.Paused;
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resumes a paused playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>True if successful.</returns>
|
||||
public async Task<bool> ResumeSessionAsync(string sessionId)
|
||||
{
|
||||
if (!_sessions.TryGetValue(sessionId, out var session))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var success = await _lmsClient.PlayAsync(session.PlayerMacs[0]).ConfigureAwait(false);
|
||||
|
||||
if (success)
|
||||
{
|
||||
session.State = PlaybackState.Playing;
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops a playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>True if successful.</returns>
|
||||
public async Task<bool> StopSessionAsync(string sessionId)
|
||||
{
|
||||
if (!_sessions.TryGetValue(sessionId, out var session))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var success = await _lmsClient.StopAsync(session.PlayerMacs[0]).ConfigureAwait(false);
|
||||
|
||||
if (success)
|
||||
{
|
||||
session.State = PlaybackState.Stopped;
|
||||
|
||||
// Unsync players if there were multiple
|
||||
if (session.PlayerMacs.Count > 1)
|
||||
{
|
||||
await _playerManager.DissolveSyncGroupAsync(session.PlayerMacs[0]).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the session
|
||||
_sessions.TryRemove(sessionId, out _);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeks to a position in the playback session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <param name="positionTicks">The position in ticks.</param>
|
||||
/// <returns>True if successful.</returns>
|
||||
public async Task<bool> SeekAsync(string sessionId, long positionTicks)
|
||||
{
|
||||
if (!_sessions.TryGetValue(sessionId, out var session))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var positionSeconds = positionTicks / TimeSpan.TicksPerSecond;
|
||||
var success = await _lmsClient.SeekAsync(session.PlayerMacs[0], positionSeconds).ConfigureAwait(false);
|
||||
|
||||
if (success)
|
||||
{
|
||||
session.PositionTicks = positionTicks;
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the volume for all players in a session.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <param name="volume">The volume level (0-100).</param>
|
||||
/// <returns>True if successful.</returns>
|
||||
public async Task<bool> SetVolumeAsync(string sessionId, int volume)
|
||||
{
|
||||
if (!_sessions.TryGetValue(sessionId, out var session))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var success = true;
|
||||
foreach (var mac in session.PlayerMacs)
|
||||
{
|
||||
if (!await _lmsClient.SetVolumeAsync(mac, volume).ConfigureAwait(false))
|
||||
{
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the session state from LMS.
|
||||
/// </summary>
|
||||
/// <param name="sessionId">The session ID.</param>
|
||||
/// <returns>A task representing the operation.</returns>
|
||||
public async Task RefreshSessionStateAsync(string sessionId)
|
||||
{
|
||||
if (!_sessions.TryGetValue(sessionId, out var session))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var status = await _lmsClient.GetPlayerStatusAsync(session.PlayerMacs[0]).ConfigureAwait(false);
|
||||
if (status == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
session.PositionTicks = (long)(status.Time * TimeSpan.TicksPerSecond);
|
||||
session.State = status.Mode switch
|
||||
{
|
||||
"play" => PlaybackState.Playing,
|
||||
"pause" => PlaybackState.Paused,
|
||||
_ => PlaybackState.Stopped
|
||||
};
|
||||
}
|
||||
|
||||
private string BuildStreamUrl(Guid itemId)
|
||||
{
|
||||
var baseUrl = Config.JellyfinServerUrl.TrimEnd('/');
|
||||
// Direct stream URL - LMS will pull audio from Jellyfin
|
||||
return $"{baseUrl}/Audio/{itemId}/stream.mp3";
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("LMS Session Manager started");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("LMS Session Manager stopping");
|
||||
|
||||
// Stop all active sessions
|
||||
foreach (var sessionId in _sessions.Keys.ToList())
|
||||
{
|
||||
_ = StopSessionAsync(sessionId);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.JellyLMS.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.JellyLMS.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Polls LMS player status to confirm state transitions.
|
||||
/// </summary>
|
||||
public class LmsStatusPoller
|
||||
{
|
||||
private readonly ILmsApiClient _lmsClient;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LmsStatusPoller"/> class.
|
||||
/// </summary>
|
||||
/// <param name="lmsClient">The LMS API client.</param>
|
||||
/// <param name="logger">The logger instance.</param>
|
||||
public LmsStatusPoller(ILmsApiClient lmsClient, ILogger logger)
|
||||
{
|
||||
_lmsClient = lmsClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private static PluginConfiguration Config => Plugin.Instance?.Configuration ?? new PluginConfiguration();
|
||||
|
||||
/// <summary>
|
||||
/// Waits for LMS to report that playback has started (mode="play").
|
||||
/// </summary>
|
||||
/// <param name="playerMac">The player's MAC address.</param>
|
||||
/// <param name="timeout">Maximum time to wait.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>True if playback started within the timeout.</returns>
|
||||
public async Task<bool> WaitForPlaybackStartAsync(
|
||||
string playerMac,
|
||||
TimeSpan timeout,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await WaitForModeAsync(playerMac, "play", timeout, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for LMS to report a specific playback mode.
|
||||
/// </summary>
|
||||
/// <param name="playerMac">The player's MAC address.</param>
|
||||
/// <param name="expectedMode">The expected mode ("play", "pause", "stop").</param>
|
||||
/// <param name="timeout">Maximum time to wait.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>True if the expected mode was detected within the timeout.</returns>
|
||||
public async Task<bool> WaitForModeAsync(
|
||||
string playerMac,
|
||||
string expectedMode,
|
||||
TimeSpan timeout,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pollInterval = TimeSpan.FromMilliseconds(Config.TransitionPollIntervalMs);
|
||||
var startTime = DateTime.UtcNow;
|
||||
|
||||
_logger.LogDebug(
|
||||
"Waiting for player {Mac} to reach mode '{Mode}' (timeout: {Timeout}s)",
|
||||
playerMac,
|
||||
expectedMode,
|
||||
timeout.TotalSeconds);
|
||||
|
||||
while (DateTime.UtcNow - startTime < timeout)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
var status = await _lmsClient.GetPlayerStatusAsync(playerMac).ConfigureAwait(false);
|
||||
if (status?.Mode == expectedMode)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Player {Mac} reached mode '{Mode}' after {Elapsed}ms",
|
||||
playerMac,
|
||||
expectedMode,
|
||||
(DateTime.UtcNow - startTime).TotalMilliseconds);
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Player {Mac} current mode: '{CurrentMode}', waiting for '{ExpectedMode}'",
|
||||
playerMac,
|
||||
status?.Mode ?? "unknown",
|
||||
expectedMode);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Error polling player {Mac} status", playerMac);
|
||||
}
|
||||
|
||||
await Task.Delay(pollInterval, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogWarning(
|
||||
"Timeout waiting for player {Mac} to reach mode '{Mode}' after {Timeout}s",
|
||||
playerMac,
|
||||
expectedMode,
|
||||
timeout.TotalSeconds);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for LMS to report a position within tolerance of the target.
|
||||
/// Used to confirm seek operations completed.
|
||||
/// </summary>
|
||||
/// <param name="playerMac">The player's MAC address.</param>
|
||||
/// <param name="targetPositionSeconds">The target position in seconds.</param>
|
||||
/// <param name="toleranceSeconds">Acceptable tolerance (default 2 seconds).</param>
|
||||
/// <param name="timeout">Maximum time to wait.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>True if the position was reached within the timeout.</returns>
|
||||
public async Task<bool> WaitForSeekCompleteAsync(
|
||||
string playerMac,
|
||||
double targetPositionSeconds,
|
||||
double toleranceSeconds,
|
||||
TimeSpan timeout,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pollInterval = TimeSpan.FromMilliseconds(Config.TransitionPollIntervalMs);
|
||||
var startTime = DateTime.UtcNow;
|
||||
|
||||
_logger.LogDebug(
|
||||
"Waiting for player {Mac} to seek to {Target}s (tolerance: {Tolerance}s, timeout: {Timeout}s)",
|
||||
playerMac,
|
||||
targetPositionSeconds,
|
||||
toleranceSeconds,
|
||||
timeout.TotalSeconds);
|
||||
|
||||
while (DateTime.UtcNow - startTime < timeout)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
var status = await _lmsClient.GetPlayerStatusAsync(playerMac).ConfigureAwait(false);
|
||||
if (status != null)
|
||||
{
|
||||
var positionDiff = Math.Abs(status.Time - targetPositionSeconds);
|
||||
if (positionDiff <= toleranceSeconds)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Player {Mac} reached position {Position}s (target: {Target}s) after {Elapsed}ms",
|
||||
playerMac,
|
||||
status.Time,
|
||||
targetPositionSeconds,
|
||||
(DateTime.UtcNow - startTime).TotalMilliseconds);
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Player {Mac} at position {Position}s, waiting for {Target}s (diff: {Diff}s)",
|
||||
playerMac,
|
||||
status.Time,
|
||||
targetPositionSeconds,
|
||||
positionDiff);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Error polling player {Mac} status during seek", playerMac);
|
||||
}
|
||||
|
||||
await Task.Delay(pollInterval, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogWarning(
|
||||
"Timeout waiting for player {Mac} to seek to {Target}s after {Timeout}s",
|
||||
playerMac,
|
||||
targetPositionSeconds,
|
||||
timeout.TotalSeconds);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes an action with automatic retry on failure.
|
||||
/// </summary>
|
||||
/// <param name="action">The async action to execute.</param>
|
||||
/// <param name="maxRetries">Maximum number of retries.</param>
|
||||
/// <param name="onRetry">Optional callback when retrying.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>True if the action succeeded within retry limit.</returns>
|
||||
public async Task<bool> ExecuteWithRetryAsync(
|
||||
Func<Task<bool>> action,
|
||||
int maxRetries,
|
||||
Action<int>? onRetry = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var retryCount = 0;
|
||||
var baseDelayMs = 500;
|
||||
|
||||
while (retryCount <= maxRetries)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
if (await action().ConfigureAwait(false))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (retryCount < maxRetries)
|
||||
{
|
||||
_logger.LogWarning(ex, "Action failed, will retry ({Retry}/{Max})", retryCount + 1, maxRetries);
|
||||
}
|
||||
|
||||
retryCount++;
|
||||
if (retryCount <= maxRetries)
|
||||
{
|
||||
onRetry?.Invoke(retryCount);
|
||||
|
||||
// Exponential backoff: 500ms, 1000ms, 2000ms, etc.
|
||||
var delayMs = baseDelayMs * (int)Math.Pow(2, retryCount - 1);
|
||||
_logger.LogDebug("Retrying in {Delay}ms (attempt {Retry}/{Max})", delayMs, retryCount, maxRetries);
|
||||
await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Jellyfin.Plugin.JellyLMS.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.JellyLMS.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Event args for state transitions.
|
||||
/// </summary>
|
||||
public class StateTransitionEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the state before the transition.
|
||||
/// </summary>
|
||||
public PlaybackState FromState { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the state after the transition.
|
||||
/// </summary>
|
||||
public PlaybackState ToState { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reason for the transition.
|
||||
/// </summary>
|
||||
public string? Reason { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Manages playback state transitions with validation.
|
||||
/// </summary>
|
||||
public class PlaybackStateMachine
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private readonly ILogger? _logger;
|
||||
private PlaybackState _currentState = PlaybackState.Idle;
|
||||
private PlaybackState _stateBeforeSeek = PlaybackState.Idle;
|
||||
|
||||
/// <summary>
|
||||
/// Valid state transitions. Key is the current state, value is the array of valid next states.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<PlaybackState, PlaybackState[]> ValidTransitions = new()
|
||||
{
|
||||
[PlaybackState.Idle] = [PlaybackState.Loading, PlaybackState.Stopped],
|
||||
[PlaybackState.Loading] = [PlaybackState.Playing, PlaybackState.Error, PlaybackState.Stopped],
|
||||
[PlaybackState.Playing] = [PlaybackState.Paused, PlaybackState.Seeking, PlaybackState.Loading, PlaybackState.Stopped, PlaybackState.Error],
|
||||
[PlaybackState.Paused] = [PlaybackState.Playing, PlaybackState.Seeking, PlaybackState.Loading, PlaybackState.Stopped, PlaybackState.Error],
|
||||
[PlaybackState.Seeking] = [PlaybackState.Playing, PlaybackState.Paused, PlaybackState.Error, PlaybackState.Stopped],
|
||||
[PlaybackState.Error] = [PlaybackState.Loading, PlaybackState.Idle, PlaybackState.Stopped],
|
||||
[PlaybackState.Stopped] = [PlaybackState.Idle, PlaybackState.Loading]
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaybackStateMachine"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Optional logger for state transitions.</param>
|
||||
public PlaybackStateMachine(ILogger? logger = null)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fired when the state changes.
|
||||
/// </summary>
|
||||
public event EventHandler<StateTransitionEventArgs>? StateChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current playback state.
|
||||
/// </summary>
|
||||
public PlaybackState CurrentState
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _currentState;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the state before the current seek operation (if in Seeking state).
|
||||
/// Used to restore the correct state after seeking completes.
|
||||
/// </summary>
|
||||
public PlaybackState StateBeforeSeek
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _stateBeforeSeek;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether playback is active (Playing or Paused).
|
||||
/// </summary>
|
||||
public bool IsPlaybackActive
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _currentState == PlaybackState.Playing
|
||||
|| _currentState == PlaybackState.Paused
|
||||
|| _currentState == PlaybackState.Seeking
|
||||
|| _currentState == PlaybackState.Loading;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to transition to a new state.
|
||||
/// </summary>
|
||||
/// <param name="newState">The target state.</param>
|
||||
/// <param name="reason">Optional reason for the transition (for logging).</param>
|
||||
/// <returns>True if the transition was valid and completed.</returns>
|
||||
public bool TryTransition(PlaybackState newState, string? reason = null)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_currentState == newState)
|
||||
{
|
||||
return true; // Already in this state
|
||||
}
|
||||
|
||||
if (!IsValidTransition(_currentState, newState))
|
||||
{
|
||||
_logger?.LogWarning(
|
||||
"Invalid state transition attempted: {From} -> {To} (reason: {Reason})",
|
||||
_currentState,
|
||||
newState,
|
||||
reason ?? "none");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store state before seek for restoration
|
||||
if (newState == PlaybackState.Seeking)
|
||||
{
|
||||
_stateBeforeSeek = _currentState;
|
||||
}
|
||||
|
||||
var oldState = _currentState;
|
||||
_currentState = newState;
|
||||
|
||||
_logger?.LogInformation(
|
||||
"State transition: {From} -> {To} (reason: {Reason})",
|
||||
oldState,
|
||||
newState,
|
||||
reason ?? "none");
|
||||
|
||||
// Fire event outside the lock to prevent deadlocks
|
||||
var args = new StateTransitionEventArgs
|
||||
{
|
||||
FromState = oldState,
|
||||
ToState = newState,
|
||||
Reason = reason
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
StateChanged?.Invoke(this, args);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogError(ex, "Error in StateChanged event handler");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forces a state change without validation. Use with caution.
|
||||
/// Intended for error recovery scenarios.
|
||||
/// </summary>
|
||||
/// <param name="newState">The target state.</param>
|
||||
/// <param name="reason">Reason for the forced transition.</param>
|
||||
public void ForceState(PlaybackState newState, string reason)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var oldState = _currentState;
|
||||
_currentState = newState;
|
||||
|
||||
_logger?.LogWarning(
|
||||
"Forced state transition: {From} -> {To} (reason: {Reason})",
|
||||
oldState,
|
||||
newState,
|
||||
reason);
|
||||
|
||||
var args = new StateTransitionEventArgs
|
||||
{
|
||||
FromState = oldState,
|
||||
ToState = newState,
|
||||
Reason = $"FORCED: {reason}"
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
StateChanged?.Invoke(this, args);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger?.LogError(ex, "Error in StateChanged event handler");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the state machine to Idle.
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
ForceState(PlaybackState.Idle, "Reset");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a transition from one state to another is valid.
|
||||
/// </summary>
|
||||
/// <param name="from">The current state.</param>
|
||||
/// <param name="to">The target state.</param>
|
||||
/// <returns>True if the transition is valid.</returns>
|
||||
public static bool IsValidTransition(PlaybackState from, PlaybackState to)
|
||||
{
|
||||
if (!ValidTransitions.TryGetValue(from, out var validTargets))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return Array.IndexOf(validTargets, to) >= 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.JellyLMS.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Injects (or removes) a script tag in the web client's <c>index.html</c>
|
||||
/// that adds a floating button linking to the JellyLMS remote control page.
|
||||
/// This follows the pattern used by other Jellyfin plugins (e.g. Intro Skipper)
|
||||
/// since there is no official plugin hook for adding buttons to the web client.
|
||||
/// </summary>
|
||||
public static class WebClientPatchService
|
||||
{
|
||||
private const string Marker = "<!-- jellylms-remote-button -->";
|
||||
private const string ScriptTag = "<script defer src=\"/JellyLms/RemoteControl/ClientScript\"></script>";
|
||||
private const string Injected = ScriptTag + Marker + "\n</body>";
|
||||
|
||||
/// <summary>
|
||||
/// Ensures the web client's index.html either has or does not have the
|
||||
/// JellyLMS remote button script injected, matching <paramref name="enableButton"/>.
|
||||
/// </summary>
|
||||
/// <param name="applicationPaths">The Jellyfin application paths.</param>
|
||||
/// <param name="enableButton">Whether the remote button script should be present.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public static void Apply(IApplicationPaths applicationPaths, bool enableButton, ILogger logger)
|
||||
{
|
||||
var indexPath = Path.Combine(applicationPaths.WebPath, "index.html");
|
||||
|
||||
try
|
||||
{
|
||||
if (!File.Exists(indexPath))
|
||||
{
|
||||
logger.LogDebug("JellyLMS: web client index.html not found at {Path}", indexPath);
|
||||
return;
|
||||
}
|
||||
|
||||
var html = File.ReadAllText(indexPath);
|
||||
var hasMarker = html.Contains(Marker, StringComparison.Ordinal);
|
||||
|
||||
if (enableButton && !hasMarker)
|
||||
{
|
||||
var patched = ReplaceLast(html, "</body>", Injected);
|
||||
File.WriteAllText(indexPath, patched);
|
||||
logger.LogInformation("JellyLMS: injected remote control button into {Path}", indexPath);
|
||||
}
|
||||
else if (!enableButton && hasMarker)
|
||||
{
|
||||
var patched = html.Replace(ScriptTag + Marker + "\n", string.Empty, StringComparison.Ordinal)
|
||||
.Replace(ScriptTag + Marker, string.Empty, StringComparison.Ordinal);
|
||||
File.WriteAllText(indexPath, patched);
|
||||
logger.LogInformation("JellyLMS: removed remote control button from {Path}", indexPath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
logger.LogWarning(ex, "JellyLMS: failed to patch web client index.html at {Path}", indexPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ReplaceLast(string source, string find, string replace)
|
||||
{
|
||||
var index = source.LastIndexOf(find, StringComparison.Ordinal);
|
||||
if (index < 0)
|
||||
{
|
||||
return source;
|
||||
}
|
||||
|
||||
return source[..index] + replace + source[(index + find.Length)..];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
<title>JellyLMS Remote</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
background: #101010;
|
||||
color: #fff;
|
||||
padding: 16px;
|
||||
padding-bottom: 60px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 1.4em;
|
||||
font-weight: 500;
|
||||
margin: 8px 0 16px;
|
||||
}
|
||||
h2 {
|
||||
font-size: 1.05em;
|
||||
font-weight: 500;
|
||||
color: #ccc;
|
||||
margin: 24px 0 8px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
.card {
|
||||
background: #1c1c1c;
|
||||
border-radius: 10px;
|
||||
padding: 14px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.player-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.player-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.player-name {
|
||||
font-weight: 500;
|
||||
font-size: 1.05em;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.player-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: #888;
|
||||
font-size: 0.85em;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.status-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
}
|
||||
.status-dot.on { background: #52b54b; }
|
||||
.status-dot.standby { background: #f9a825; }
|
||||
.status-dot.off { background: #f44336; }
|
||||
.power-btn {
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
font-size: 1.2em;
|
||||
background: #2a2a2a;
|
||||
color: #aaa;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.power-btn.on {
|
||||
background: #00a4dc;
|
||||
color: #fff;
|
||||
}
|
||||
.volume-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.volume-row input[type="range"] {
|
||||
flex: 1;
|
||||
}
|
||||
.volume-value {
|
||||
width: 2.5em;
|
||||
text-align: right;
|
||||
color: #ccc;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.sync-group-players {
|
||||
color: #ccc;
|
||||
flex: 1;
|
||||
}
|
||||
.sync-checkbox-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 0;
|
||||
}
|
||||
button.action {
|
||||
background: #00a4dc;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 8px 14px;
|
||||
font-size: 0.95em;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.action:disabled {
|
||||
background: #333;
|
||||
color: #777;
|
||||
cursor: default;
|
||||
}
|
||||
button.action.alt {
|
||||
background: #333;
|
||||
color: #ccc;
|
||||
}
|
||||
.empty, .message {
|
||||
color: #888;
|
||||
padding: 8px 0;
|
||||
}
|
||||
.message.error { color: #f44336; }
|
||||
.message a { color: #00a4dc; }
|
||||
#refreshBtn {
|
||||
position: fixed;
|
||||
bottom: 16px;
|
||||
right: 16px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>🔊 JellyLMS Remote</h1>
|
||||
<div id="app">
|
||||
<p class="message">Loading…</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
var API_BASE = '/JellyLms';
|
||||
var state = { players: [], syncGroups: [] };
|
||||
|
||||
function getAuthToken() {
|
||||
try {
|
||||
var creds = JSON.parse(localStorage.getItem('jellyfin_credentials'));
|
||||
var server = creds && creds.Servers && creds.Servers[0];
|
||||
return (server && server.AccessToken) || null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function api(path, options) {
|
||||
options = options || {};
|
||||
var headers = options.headers || {};
|
||||
var token = getAuthToken();
|
||||
if (token) {
|
||||
headers['X-Emby-Token'] = token;
|
||||
}
|
||||
|
||||
if (options.body) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
|
||||
return fetch(API_BASE + path, {
|
||||
method: options.method || 'GET',
|
||||
headers: headers,
|
||||
body: options.body
|
||||
}).then(function (resp) {
|
||||
if (!resp.ok) {
|
||||
var err = new Error('Request failed: ' + resp.status);
|
||||
err.status = resp.status;
|
||||
throw err;
|
||||
}
|
||||
|
||||
if (resp.status === 204) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var contentType = resp.headers.get('content-type') || '';
|
||||
return contentType.indexOf('application/json') !== -1 ? resp.json() : null;
|
||||
});
|
||||
}
|
||||
|
||||
function renderMessage(text, isError) {
|
||||
document.getElementById('app').innerHTML =
|
||||
'<p class="message' + (isError ? ' error' : '') + '">' + text + '</p>';
|
||||
}
|
||||
|
||||
function getStatusClass(player) {
|
||||
if (!player.IsConnected) return 'off';
|
||||
return player.IsPoweredOn ? 'on' : 'standby';
|
||||
}
|
||||
|
||||
function getStatusText(player) {
|
||||
if (!player.IsConnected) return 'Disconnected';
|
||||
return player.IsPoweredOn ? 'Playing' : 'Standby';
|
||||
}
|
||||
|
||||
function syncedMacs() {
|
||||
var macs = new Set();
|
||||
state.syncGroups.forEach(function (group) {
|
||||
macs.add(group.MasterMac);
|
||||
group.SlaveMacs.forEach(function (mac) { macs.add(mac); });
|
||||
});
|
||||
return macs;
|
||||
}
|
||||
|
||||
function findPlayer(mac) {
|
||||
return state.players.find(function (p) { return p.MacAddress === mac; });
|
||||
}
|
||||
|
||||
function render() {
|
||||
var app = document.getElementById('app');
|
||||
var html = '';
|
||||
|
||||
html += '<h2>Players</h2>';
|
||||
if (state.players.length === 0) {
|
||||
html += '<p class="empty">No players found.</p>';
|
||||
} else {
|
||||
state.players.forEach(function (player) {
|
||||
var mac = player.MacAddress;
|
||||
html += '<div class="card">';
|
||||
html += '<div class="player-row">';
|
||||
html += '<div class="player-info">';
|
||||
html += '<div class="player-name">' + player.Name + '</div>';
|
||||
html += '<div class="player-status"><span class="status-dot ' + getStatusClass(player) + '"></span>' +
|
||||
'<span>' + getStatusText(player) + '</span></div>';
|
||||
html += '</div>';
|
||||
html += '<button class="power-btn' + (player.IsPoweredOn ? ' on' : '') + '" data-action="power" data-mac="' + mac + '" data-on="' + player.IsPoweredOn + '" title="Power">⏻</button>';
|
||||
html += '</div>';
|
||||
html += '<div class="volume-row">';
|
||||
html += '<span>🔈</span>';
|
||||
html += '<input type="range" min="0" max="100" value="' + player.Volume + '" data-action="volume" data-mac="' + mac + '">';
|
||||
html += '<span class="volume-value">' + player.Volume + '</span>';
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
});
|
||||
}
|
||||
|
||||
html += '<h2>Multi-Room Sync</h2>';
|
||||
if (state.syncGroups.length > 0) {
|
||||
state.syncGroups.forEach(function (group) {
|
||||
var names = [];
|
||||
var master = findPlayer(group.MasterMac);
|
||||
if (master) names.push(master.Name);
|
||||
group.SlaveMacs.forEach(function (mac) {
|
||||
var p = findPlayer(mac);
|
||||
if (p) names.push(p.Name);
|
||||
});
|
||||
|
||||
html += '<div class="card">';
|
||||
html += '<div class="player-row">';
|
||||
html += '<span class="sync-group-players">' + names.join(' + ') + '</span>';
|
||||
html += '<button class="action alt" data-action="unsync" data-master="' + group.MasterMac + '">Unsync</button>';
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
});
|
||||
}
|
||||
|
||||
var unsynced = state.players.filter(function (p) { return !syncedMacs().has(p.MacAddress); });
|
||||
if (unsynced.length > 1) {
|
||||
html += '<div class="card">';
|
||||
html += '<p class="empty" style="margin-top:0;">Select players to sync together:</p>';
|
||||
unsynced.forEach(function (player) {
|
||||
html += '<label class="sync-checkbox-row">';
|
||||
html += '<input type="checkbox" data-action="sync-select" data-mac="' + player.MacAddress + '">';
|
||||
html += '<span>' + player.Name + '</span>';
|
||||
html += '</label>';
|
||||
});
|
||||
html += '<div style="margin-top:10px;">';
|
||||
html += '<button class="action" id="syncSelectedBtn" disabled>Sync Selected</button>';
|
||||
html += '</div>';
|
||||
html += '</div>';
|
||||
} else if (state.syncGroups.length === 0) {
|
||||
html += '<p class="empty">No players synced yet.</p>';
|
||||
}
|
||||
|
||||
app.innerHTML = html;
|
||||
attachHandlers();
|
||||
}
|
||||
|
||||
function attachHandlers() {
|
||||
document.querySelectorAll('[data-action="power"]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var mac = btn.getAttribute('data-mac');
|
||||
var isOn = btn.getAttribute('data-on') === 'true';
|
||||
var endpoint = isOn ? '/Players/' + encodeURIComponent(mac) + '/PowerOff' : '/Players/' + encodeURIComponent(mac) + '/PowerOn';
|
||||
btn.disabled = true;
|
||||
api(endpoint, { method: 'POST' }).then(loadPlayers).catch(function () {
|
||||
btn.disabled = false;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-action="volume"]').forEach(function (input) {
|
||||
input.addEventListener('change', function () {
|
||||
var mac = input.getAttribute('data-mac');
|
||||
var volume = parseInt(input.value, 10);
|
||||
input.nextElementSibling.textContent = volume;
|
||||
api('/Players/' + encodeURIComponent(mac) + '/Volume', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ Volume: volume })
|
||||
}).catch(function () {});
|
||||
});
|
||||
input.addEventListener('input', function () {
|
||||
input.nextElementSibling.textContent = input.value;
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-action="unsync"]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var masterMac = btn.getAttribute('data-master');
|
||||
btn.disabled = true;
|
||||
api('/SyncGroups/' + encodeURIComponent(masterMac), { method: 'DELETE' })
|
||||
.then(loadAll)
|
||||
.catch(function () { btn.disabled = false; });
|
||||
});
|
||||
});
|
||||
|
||||
var syncBtn = document.getElementById('syncSelectedBtn');
|
||||
if (syncBtn) {
|
||||
var checkboxes = document.querySelectorAll('[data-action="sync-select"]');
|
||||
var updateSyncBtn = function () {
|
||||
var checked = Array.from(checkboxes).filter(function (cb) { return cb.checked; });
|
||||
syncBtn.disabled = checked.length < 2;
|
||||
};
|
||||
checkboxes.forEach(function (cb) { cb.addEventListener('change', updateSyncBtn); });
|
||||
|
||||
syncBtn.addEventListener('click', function () {
|
||||
var macs = Array.from(checkboxes).filter(function (cb) { return cb.checked; })
|
||||
.map(function (cb) { return cb.getAttribute('data-mac'); });
|
||||
if (macs.length < 2) return;
|
||||
|
||||
syncBtn.disabled = true;
|
||||
api('/SyncGroups', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ MasterMac: macs[0], SlaveMacs: macs.slice(1) })
|
||||
}).then(loadAll).catch(function () { syncBtn.disabled = false; });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function loadPlayers() {
|
||||
return api('/Players?refresh=true').then(function (players) {
|
||||
state.players = players || [];
|
||||
render();
|
||||
});
|
||||
}
|
||||
|
||||
function loadSyncGroups() {
|
||||
return api('/SyncGroups').then(function (groups) {
|
||||
state.syncGroups = groups || [];
|
||||
});
|
||||
}
|
||||
|
||||
function loadAll() {
|
||||
return Promise.all([loadPlayers(), loadSyncGroups()]).then(render);
|
||||
}
|
||||
|
||||
function init() {
|
||||
if (!getAuthToken()) {
|
||||
renderMessage('Please <a href="/web/">log in to Jellyfin</a> first, then reload this page.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
api('/RemoteControl/Access').then(function () {
|
||||
loadAll().catch(function () {
|
||||
renderMessage('Failed to load players. Check the JellyLMS plugin configuration.', true);
|
||||
});
|
||||
}).catch(function (err) {
|
||||
if (err.status === 403) {
|
||||
renderMessage('Your account does not have permission to use the multi-room remote. Ask an admin to grant "Allow remote control of other users".', true);
|
||||
} else {
|
||||
renderMessage('Could not reach JellyLMS. <a href="/web/">Return to Jellyfin</a>.', true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,49 @@
|
||||
(function () {
|
||||
function getAuthToken() {
|
||||
try {
|
||||
var creds = JSON.parse(localStorage.getItem('jellyfin_credentials'));
|
||||
var server = creds && creds.Servers && creds.Servers[0];
|
||||
return (server && server.AccessToken) || null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function addButton() {
|
||||
if (document.getElementById('jellylms-remote-btn')) {
|
||||
return;
|
||||
}
|
||||
|
||||
var btn = document.createElement('a');
|
||||
btn.id = 'jellylms-remote-btn';
|
||||
btn.href = '/JellyLms/RemoteControl';
|
||||
btn.title = 'Multi-room Remote';
|
||||
btn.textContent = '🔊';
|
||||
btn.style.cssText = 'position:fixed;bottom:20px;right:20px;width:48px;height:48px;' +
|
||||
'border-radius:50%;background:#00a4dc;color:#fff;display:flex;' +
|
||||
'align-items:center;justify-content:center;font-size:22px;' +
|
||||
'text-decoration:none;z-index:99999;box-shadow:0 2px 8px rgba(0,0,0,0.5);';
|
||||
document.body.appendChild(btn);
|
||||
}
|
||||
|
||||
function init() {
|
||||
var token = getAuthToken();
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('/JellyLms/RemoteControl/Access', { headers: { 'X-Emby-Token': token } })
|
||||
.then(function (resp) {
|
||||
if (resp.ok) {
|
||||
addButton();
|
||||
}
|
||||
})
|
||||
.catch(function () {});
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -2,6 +2,20 @@
|
||||
|
||||
A Jellyfin plugin that bridges audio playback to Logitech Media Server (LMS) for multi-room synchronized playback.
|
||||
|
||||
## Quick Install
|
||||
|
||||
Add the following repository URL to your Jellyfin server to install JellyLMS directly from the plugin catalog:
|
||||
|
||||
```
|
||||
https://gitea.tourolle.paris/dtourolle/jellyLMS/raw/branch/master/manifest.json
|
||||
```
|
||||
|
||||
**Steps:**
|
||||
1. Go to **Dashboard** → **Plugins** → **Repositories**
|
||||
2. Click **Add** and paste the URL above
|
||||
3. Go to **Catalog** and find "JellyLMS"
|
||||
4. Click **Install** and restart Jellyfin
|
||||
|
||||
## Overview
|
||||
|
||||
JellyLMS enables Jellyfin to stream audio to LMS, which acts as a multi-room speaker system. The architecture is:
|
||||
@@ -17,15 +31,15 @@ JellyLMS enables Jellyfin to stream audio to LMS, which acts as a multi-room spe
|
||||
│ │ Library │──┼────────►│ LmsApiClient │────────►│ │ Players │ │
|
||||
│ │ (Audio) │ │ │ │ │ │ (Zones) │ │
|
||||
│ └───────────┘ │ │ ┌───────────┐ │ │ └───────────┘ │
|
||||
│ │ │ │ Session │ │ │ │
|
||||
│ ┌───────────┐ │ │ │ Manager │ │ │ ┌───────────┐ │
|
||||
│ │ Queue │──┼────────►│ └───────────┘ │────────►│ │ Sync │ │
|
||||
│ │ │ │ │ │ │ │ Groups │ │
|
||||
│ └───────────┘ │ │ ┌───────────┐ │ │ └───────────┘ │
|
||||
│ │ │ │ REST API │ │ │ │
|
||||
│ ┌───────────┐ │ │ │Controller │ │ │ │
|
||||
│ │ Playback │──┼────────►│ └───────────┘ │ │ │
|
||||
│ │ Controls │ │ │ │ │ │
|
||||
│ │ │ │ Session │ │ │ │
|
||||
│ ┌───────────┐ │ │ │Controller │ │ │ ┌───────────┐ │
|
||||
│ │ Queue │──┼────────►│ │ (State │ │────────►│ │ Sync │ │
|
||||
│ │ │ │ │ │ Machine) │ │ │ │ Groups │ │
|
||||
│ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │
|
||||
│ │ │ │ │ │
|
||||
│ ┌───────────┐ │ │ ┌───────────┐ │ │ │
|
||||
│ │ Playback │──┼────────►│ │ REST API │ │ │ │
|
||||
│ │ Controls │ │ │ └───────────┘ │ │ │
|
||||
│ └───────────┘ │ └─────────────────┘ └─────────────────┘
|
||||
└─────────────────┘
|
||||
```
|
||||
@@ -34,15 +48,91 @@ JellyLMS enables Jellyfin to stream audio to LMS, which acts as a multi-room spe
|
||||
|
||||
- **Player Discovery**: Automatically discovers all LMS players/zones
|
||||
- **Multi-Room Sync**: Create and manage sync groups for synchronized playback across multiple rooms
|
||||
- **Playback Control**: Play, pause, stop, seek, and volume control forwarded to LMS
|
||||
- **Playback Control**: Play, pause, stop, seek, and volume control via Jellyfin's "Play On" (cast) interface
|
||||
- **Stream Bridging**: Generates audio stream URLs from Jellyfin for LMS to consume
|
||||
- **Robust State Machine**: Ensures proper sequencing of playback operations with automatic retry and timeout handling
|
||||
|
||||
## Screenshots
|
||||
|
||||
### Cast to LMS Players
|
||||
Select any LMS player directly from Jellyfin's "Play On" menu:
|
||||
|
||||

|
||||
|
||||
### Plugin Configuration
|
||||
Configure LMS and Jellyfin server connections:
|
||||
|
||||

|
||||
|
||||
### Player Discovery
|
||||
View discovered LMS players with their status and volume levels:
|
||||
|
||||

|
||||
|
||||
### Sync Group Management
|
||||
Create and manage synchronized playback groups for multi-room audio:
|
||||
|
||||

|
||||
|
||||
## Requirements
|
||||
|
||||
- Jellyfin Server 10.10.0 or later
|
||||
- .NET 8.0 Runtime
|
||||
- .NET 9.0 Runtime
|
||||
- Logitech Media Server (LMS) with JSON-RPC API enabled (default on port 9000)
|
||||
|
||||
## Playback Architecture
|
||||
|
||||
JellyLMS uses Jellyfin's native "Play On" (cast) interface to control LMS players. When you select an LMS player from Jellyfin's cast menu, playback is managed through a robust state machine that ensures reliable operation.
|
||||
|
||||
### State Machine
|
||||
|
||||
The playback controller uses a state machine to ensure proper sequencing of operations:
|
||||
|
||||
```
|
||||
┌────────┐
|
||||
│ Idle │ (device connected, no media)
|
||||
└───┬────┘
|
||||
│ Play command
|
||||
▼
|
||||
┌────────┐
|
||||
┌────►│Loading │◄────┐
|
||||
│ └───┬────┘ │
|
||||
│ │ │ Seek (HTTP streaming
|
||||
│ LMS confirms │ restarts stream)
|
||||
│ mode="play" │
|
||||
│ ▼ │
|
||||
┌───────┐ │ ┌────────┐ │
|
||||
│ Error │◄────┼─────│Playing │─────┘
|
||||
└───┬───┘ │ └───┬────┘
|
||||
│ │ │ Pause
|
||||
retry │ ▼
|
||||
│ │ ┌────────┐
|
||||
└─────────┼─────│ Paused │
|
||||
│ └───┬────┘
|
||||
│ │ Seek (native LMS)
|
||||
│ ▼
|
||||
│ ┌────────┐
|
||||
└─────│Seeking │
|
||||
└────────┘
|
||||
|
||||
From any state: Stop → Stopped
|
||||
```
|
||||
|
||||
### How Playback Works
|
||||
|
||||
1. **Cast Request**: User selects an LMS player from Jellyfin's "Play On" menu
|
||||
2. **Loading**: Plugin sends play command to LMS and transitions to Loading state
|
||||
3. **Confirmation**: Plugin polls LMS until playback is confirmed (mode="play")
|
||||
4. **Playing**: Playback is active; progress is synced between Jellyfin and LMS
|
||||
5. **Controls**: Play, pause, seek, and volume commands are forwarded to LMS
|
||||
|
||||
### Error Handling
|
||||
|
||||
The state machine includes automatic retry with exponential backoff:
|
||||
- **Timeout errors**: Auto-retry up to 2 times (500ms → 1s delay)
|
||||
- **Network errors**: Auto-retry up to 2 times
|
||||
- **LMS errors**: No retry, transition to Error state
|
||||
|
||||
## Installation
|
||||
|
||||
### Manual Installation
|
||||
@@ -65,7 +155,7 @@ cd jellyLMS
|
||||
dotnet build Jellyfin.Plugin.JellyLMS.sln -c Release
|
||||
|
||||
# The DLL will be in:
|
||||
# Jellyfin.Plugin.JellyLMS/bin/Release/net8.0/
|
||||
# Jellyfin.Plugin.JellyLMS/bin/Release/net9.0/
|
||||
```
|
||||
|
||||
## Configuration
|
||||
@@ -80,41 +170,45 @@ dotnet build Jellyfin.Plugin.JellyLMS.sln -c Release
|
||||
| Connection Timeout | Timeout for LMS API calls (seconds) | `10` |
|
||||
| Enable Auto Sync | Automatically sync players when creating groups | `true` |
|
||||
| Default Player | MAC address of the default player | (none) |
|
||||
| Use Direct File Path | Enable direct file access instead of HTTP streaming | `false` |
|
||||
|
||||
### Advanced Settings (State Machine)
|
||||
|
||||
| Setting | Description | Default |
|
||||
|---------|-------------|---------|
|
||||
| Loading Timeout | Max time to wait for LMS to start playback (seconds) | `5` |
|
||||
| Seek Timeout | Max time to wait for seek to complete (seconds) | `3` |
|
||||
| Transition Poll Interval | How often to poll LMS during state transitions (ms) | `300` |
|
||||
| Max Auto Retries | Number of automatic retries for transient failures | `2` |
|
||||
|
||||
3. Click "Test Connection" to verify connectivity to LMS
|
||||
4. Use "Discover Players" to see available LMS players
|
||||
|
||||
## API Endpoints
|
||||
|
||||
The plugin exposes REST API endpoints under `/JellyLms/`:
|
||||
The plugin exposes REST API endpoints under `/JellyLms/` for player and sync group management.
|
||||
|
||||
**Note:** Playback control (play, pause, seek, volume) is handled through Jellyfin's native "Play On" (cast) interface, not through REST endpoints.
|
||||
|
||||
### Players
|
||||
|
||||
- `GET /JellyLms/Players` - List all LMS players
|
||||
- `GET /JellyLms/Players/{mac}` - Get specific player details
|
||||
- `POST /JellyLms/Players/Refresh` - Refresh player list from LMS
|
||||
- `POST /JellyLms/Players/{mac}/PowerOn` - Power on a player
|
||||
- `POST /JellyLms/Players/{mac}/PowerOff` - Power off a player
|
||||
- `POST /JellyLms/Players/{mac}/Volume` - Set player volume
|
||||
|
||||
### Sync Groups
|
||||
|
||||
- `GET /JellyLms/SyncGroups` - List all sync groups
|
||||
- `POST /JellyLms/SyncGroups` - Create a new sync group
|
||||
- `DELETE /JellyLms/SyncGroups/{masterMac}` - Dissolve a sync group
|
||||
- `DELETE /JellyLms/SyncGroups/{masterMac}/Players/{slaveMac}` - Remove player from group
|
||||
- `DELETE /JellyLms/SyncGroups/Players/{mac}` - Remove player from its sync group
|
||||
|
||||
### Sessions
|
||||
### Utilities
|
||||
|
||||
- `GET /JellyLms/Sessions` - List active playback sessions
|
||||
- `POST /JellyLms/Sessions` - Start a new playback session
|
||||
- `POST /JellyLms/Sessions/{id}/Pause` - Pause playback
|
||||
- `POST /JellyLms/Sessions/{id}/Resume` - Resume playback
|
||||
- `POST /JellyLms/Sessions/{id}/Stop` - Stop playback
|
||||
- `POST /JellyLms/Sessions/{id}/Seek` - Seek to position
|
||||
- `POST /JellyLms/Sessions/{id}/Volume` - Set volume
|
||||
|
||||
### Status
|
||||
|
||||
- `GET /JellyLms/Status` - Get LMS connection status
|
||||
- `POST /JellyLms/TestConnection` - Test LMS connectivity
|
||||
- `GET /JellyLms/DiscoverPaths` - Discover file paths for direct file access configuration
|
||||
|
||||
## LMS Setup
|
||||
|
||||
@@ -146,6 +240,30 @@ The plugin communicates with LMS using the `slim.request` JSON-RPC method.
|
||||
2. Check that audio files are in a format supported by your LMS players
|
||||
3. Ensure players are powered on (plugin can auto-power-on if configured)
|
||||
|
||||
## Known Limitations
|
||||
|
||||
### Seeking with HTTP Streaming
|
||||
|
||||
When using HTTP streaming (the default), LMS cannot seek within audio streams. To work around this, when you seek or cast from a specific position, JellyLMS restarts playback with a new transcoded stream that begins at the requested position. This means:
|
||||
|
||||
- **Seeking triggers a brief audio restart** rather than a smooth jump
|
||||
- **Starting playback mid-track** uses transcoding (MP3 320kbps) instead of direct streaming
|
||||
- **Playback from the beginning** uses direct/static streaming for best quality
|
||||
|
||||
This is a fundamental limitation of how LMS handles HTTP streams.
|
||||
|
||||
### Solution: Direct File Access
|
||||
|
||||
If your Jellyfin and LMS servers can both access the same storage (e.g., a NAS), you can enable **Direct File Access** mode in the plugin settings. This allows LMS to read files directly from disk, enabling:
|
||||
|
||||
- **Native smooth seeking** - no audio restart when scrubbing
|
||||
- **Full quality playback** - no transcoding needed
|
||||
- **Better performance** - no HTTP overhead
|
||||
|
||||
To configure, set the path mappings in the plugin settings:
|
||||
- **Jellyfin Media Path**: The path prefix as Jellyfin sees your library (e.g., `/media/music`)
|
||||
- **LMS Media Path**: The same location as LMS sees it (e.g., `/mnt/music` or `//nas/music`)
|
||||
|
||||
## Development
|
||||
|
||||
### Project Structure
|
||||
@@ -158,15 +276,17 @@ Jellyfin.Plugin.JellyLMS/
|
||||
│ ├── PluginConfiguration.cs # Plugin settings
|
||||
│ └── configPage.html # Dashboard configuration UI
|
||||
├── Api/
|
||||
│ └── JellyLmsController.cs # REST API endpoints
|
||||
│ └── JellyLmsController.cs # REST API endpoints (players, sync groups)
|
||||
├── Services/
|
||||
│ ├── ILmsApiClient.cs # LMS API interface
|
||||
│ ├── LmsApiClient.cs # LMS JSON-RPC client
|
||||
│ ├── LmsPlayerManager.cs # Player discovery & sync
|
||||
│ └── LmsSessionManager.cs # Playback session management
|
||||
│ ├── LmsSessionController.cs # Playback control (ISessionController)
|
||||
│ ├── PlaybackStateMachine.cs # State machine for playback lifecycle
|
||||
│ └── LmsStatusPoller.cs # Polls LMS to confirm state transitions
|
||||
└── Models/
|
||||
├── LmsPlayer.cs # Player model
|
||||
├── LmsPlaybackSession.cs # Session state model
|
||||
├── LmsPlaybackSession.cs # Session state (incl. PlaybackState enum)
|
||||
└── LmsApiModels.cs # JSON-RPC DTOs
|
||||
```
|
||||
|
||||
@@ -177,7 +297,7 @@ Jellyfin.Plugin.JellyLMS/
|
||||
dotnet build Jellyfin.Plugin.JellyLMS.sln
|
||||
|
||||
# Copy to Jellyfin plugins directory
|
||||
cp Jellyfin.Plugin.JellyLMS/bin/Debug/net8.0/Jellyfin.Plugin.JellyLMS.dll \
|
||||
cp Jellyfin.Plugin.JellyLMS/bin/Debug/net9.0/Jellyfin.Plugin.JellyLMS.dll \
|
||||
~/.local/share/jellyfin/plugins/JellyLMS/
|
||||
|
||||
# Restart Jellyfin to load the plugin
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 84 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 127 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 50 KiB |
@@ -0,0 +1,36 @@
|
||||
[
|
||||
{
|
||||
"guid": "a5b8c9d0-1e2f-3a4b-5c6d-7e8f9a0b1c2d",
|
||||
"name": "JellyLMS",
|
||||
"description": "Stream Jellyfin audio to Logitech Media Server (LMS) for multi-room playback",
|
||||
"overview": "Bridges Jellyfin audio playback to LMS for synchronized multi-room playback across Squeezebox players",
|
||||
"owner": "dtourolle",
|
||||
"category": "Music",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.0.2",
|
||||
"changelog": "Release 1.0.2",
|
||||
"targetAbi": "10.10.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellyLMS/releases/download/v1.0.2/jellylms_1.0.2.0.zip",
|
||||
"checksum": "43e4fcd6dc67be82a1e9d8816cdf00df",
|
||||
"timestamp": "2026-01-25T18:35:06Z"
|
||||
},
|
||||
{
|
||||
"version": "1.0.1",
|
||||
"changelog": "Release 1.0.1",
|
||||
"targetAbi": "10.10.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellyLMS/releases/download/v1.0.1/jellylms_1.0.1.0.zip",
|
||||
"checksum": "093a1821b86a220cdfad49c3d93345a7",
|
||||
"timestamp": "2025-12-30T13:43:10Z"
|
||||
},
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"changelog": "Release 1.0.0",
|
||||
"targetAbi": "10.10.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellyLMS/releases/download/v1.0.0/jellylms_1.0.0.0.zip",
|
||||
"checksum": "b6194d5ceb5ec0ea711a48f6d34a290d",
|
||||
"timestamp": "2025-12-20T13:54:14Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user