diff --git a/.gitea/workflows/build.yaml b/.gitea/workflows/build.yaml new file mode 100644 index 0000000..7461def --- /dev/null +++ b/.gitea/workflows/build.yaml @@ -0,0 +1,89 @@ +name: '๐Ÿ—๏ธ Build Plugin' + +on: + push: + branches: + - master + paths-ignore: + - '**/*.md' + pull_request: + branches: + - master + paths-ignore: + - '**/*.md' + workflow_dispatch: + +jobs: + build: + runs-on: linux/amd64 + container: + image: gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + path: build-${{ github.run_id }} + + - name: Cache NuGet packages + uses: actions/cache@v3 + with: + path: ~/.nuget/packages + key: nuget-${{ hashFiles('**/Jellyfin.Plugin.WatchedTogether.csproj', '**/Jellyfin.Plugin.WatchedTogether.Tests.csproj') }} + restore-keys: nuget- + + - name: Restore dependencies + working-directory: build-${{ github.run_id }} + run: dotnet restore Jellyfin.Plugin.WatchedTogether.sln + + - name: Compute build version + id: version + run: | + # Date-based version so a side-loaded build is identifiable in Jellyfin. + DATE=$(date -u +"%Y%m%d") + VERSION="1.0.${DATE}.${{ github.run_number }}" + if [ -n "${{ github.event.pull_request.number }}" ]; then + LABEL="pr${{ github.event.pull_request.number }}" + else + LABEL="master" + fi + echo "version=${VERSION}" >> $GITHUB_OUTPUT + echo "label=${LABEL}" >> $GITHUB_OUTPUT + echo "Build version: ${VERSION} (${LABEL})" + + - name: Set build version + working-directory: build-${{ github.run_id }} + run: | + sed -i "s/^version:.*/version: \"${{ steps.version.outputs.version }}\"/" build.yaml + + - name: Build solution + working-directory: build-${{ github.run_id }} + run: dotnet build Jellyfin.Plugin.WatchedTogether.sln --configuration Release --no-restore --no-self-contained /m:1 + + - name: Run tests + working-directory: build-${{ github.run_id }} + run: dotnet test Jellyfin.Plugin.WatchedTogether.sln --no-build --configuration Release --verbosity normal + + - name: Build Jellyfin Plugin + id: jprm + working-directory: build-${{ github.run_id }} + run: | + mkdir -p artifacts + jprm --verbosity=debug plugin build . + ARTIFACT=$(find . -name "*.zip" -type f -print -quit | sed 's|^\./||') + LATEST="artifacts/watchedtogether_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: watchedtogether-${{ steps.version.outputs.label }}-${{ steps.version.outputs.version }} + 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 }} diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml new file mode 100644 index 0000000..f7f2dd4 --- /dev/null +++ b/.gitea/workflows/release.yaml @@ -0,0 +1,166 @@ +name: '๐Ÿš€ Release Plugin' + +on: + push: + tags: + - 'v*.*.*' + workflow_dispatch: + inputs: + version: + description: 'Version to release (e.g., v1.0.0)' + required: true + type: string + +jobs: + build-and-release: + runs-on: linux/amd64 + container: + image: gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + path: release-${{ github.run_id }} + + - name: Get version + id: get_version + run: | + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + VERSION="${{ github.event.inputs.version }}" + else + VERSION="${GITHUB_REF#refs/tags/}" + fi + echo "version=${VERSION}" >> $GITHUB_OUTPUT + echo "version_number=${VERSION#v}" >> $GITHUB_OUTPUT + 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.WatchedTogether.csproj', '**/Jellyfin.Plugin.WatchedTogether.Tests.csproj') }} + restore-keys: nuget- + + - name: Restore dependencies + working-directory: release-${{ github.run_id }} + run: dotnet restore Jellyfin.Plugin.WatchedTogether.sln + + - name: Build solution + working-directory: release-${{ github.run_id }} + run: dotnet build Jellyfin.Plugin.WatchedTogether.sln --configuration Release --no-restore --no-self-contained /m:1 + + - name: Run tests + working-directory: release-${{ github.run_id }} + run: dotnet test Jellyfin.Plugin.WatchedTogether.sln --no-build --configuration Release --verbosity normal + + - name: Build Jellyfin Plugin + id: jprm + working-directory: release-${{ github.run_id }} + run: | + mkdir -p artifacts + 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: 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 "Checksum: ${CHECKSUM}" + + - name: Create Release + working-directory: release-${{ github.run_id }} + env: + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REPO_OWNER="${{ github.repository_owner }}" + REPO_NAME="${{ github.event.repository.name }}" + GITEA_URL="${{ github.server_url }}" + 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 "$(jq -n --arg tag "$VERSION" --arg name "Release $VERSION" --arg body "Watched Together Jellyfin plugin. See attached files for installation." '{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')") + + HTTP_CODE=$(echo "$RESPONSE" | tail -n1) + BODY=$(echo "$RESPONSE" | sed '$d') + + if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then + RELEASE_ID=$(echo "$BODY" | jq -r '.id') + echo "Created release with ID: ${RELEASE_ID}" + else + echo "Failed to create release. HTTP ${HTTP_CODE}" + echo "$BODY" + exit 1 + fi + + echo "Uploading plugin artifact..." + curl -f -X POST \ + -H "Authorization: token ${GITEA_TOKEN}" \ + -H "Content-Type: application/zip" \ + --data-binary "@${{ steps.jprm.outputs.artifact }}" \ + "${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/releases/${RELEASE_ID}/assets?name=${{ steps.jprm.outputs.artifact_name }}" + + echo "Uploading build.yaml..." + curl -f -X POST \ + -H "Authorization: token ${GITEA_TOKEN}" \ + -H "Content-Type: application/x-yaml" \ + --data-binary "@build.yaml" \ + "${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/releases/${RELEASE_ID}/assets?name=build.yaml" + + echo "โœ… Release created successfully!" + + - name: Update manifest.json + working-directory: release-${{ github.run_id }} + env: + GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REPO_OWNER="${{ github.repository_owner }}" + REPO_NAME="${{ github.event.repository.name }}" + GITEA_URL="${{ github.server_url }}" + VERSION="${{ steps.get_version.outputs.version_number }}" + CHECKSUM="${{ steps.checksum.outputs.checksum }}" + ARTIFACT_NAME="${{ steps.jprm.outputs.artifact_name }}" + TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ") + DOWNLOAD_URL="${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/releases/download/${{ steps.get_version.outputs.version }}/${ARTIFACT_NAME}" + + git config user.name "Gitea Actions" + git config user.email "actions@gitea.tourolle.paris" + git fetch origin master + git checkout master + + NEW_VERSION=$(cat < manifest.tmp && mv manifest.tmp manifest.json + git add manifest.json + git commit -m "Update manifest.json for version ${VERSION}" + git push origin master + + - name: Cleanup + if: always() + run: rm -rf release-${{ github.run_id }} diff --git a/.gitea/workflows/test.yaml b/.gitea/workflows/test.yaml new file mode 100644 index 0000000..c7e7900 --- /dev/null +++ b/.gitea/workflows/test.yaml @@ -0,0 +1,59 @@ +name: '๐Ÿงช Test Plugin' + +on: + push: + branches: + - master + - develop + paths-ignore: + - '**/*.md' + pull_request: + branches: + - master + - develop + paths-ignore: + - '**/*.md' + workflow_dispatch: + +jobs: + test: + runs-on: linux/amd64 + container: + image: gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + path: test-${{ github.run_id }} + + - name: Cache NuGet packages + uses: actions/cache@v3 + with: + path: ~/.nuget/packages + key: nuget-${{ hashFiles('**/Jellyfin.Plugin.WatchedTogether.csproj', '**/Jellyfin.Plugin.WatchedTogether.Tests.csproj') }} + restore-keys: nuget- + + - name: Restore dependencies + working-directory: test-${{ github.run_id }} + run: dotnet restore Jellyfin.Plugin.WatchedTogether.sln + + - name: Build solution + working-directory: test-${{ github.run_id }} + run: dotnet build Jellyfin.Plugin.WatchedTogether.sln --configuration Debug --no-restore --no-self-contained /m:1 + + - name: Run tests + working-directory: test-${{ github.run_id }} + run: dotnet test Jellyfin.Plugin.WatchedTogether.sln --no-build --configuration Debug --verbosity normal --logger "trx;LogFileName=test-results.trx" + + - name: Upload test results + if: always() + uses: actions/upload-artifact@v3 + with: + name: test-results + path: test-${{ github.run_id }}/**/test-results.trx + retention-days: 7 + + - name: Cleanup + if: always() + run: rm -rf test-${{ github.run_id }} diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml deleted file mode 100644 index f290747..0000000 --- a/.github/workflows/build.yaml +++ /dev/null @@ -1,18 +0,0 @@ -name: '๐Ÿ—๏ธ Build Plugin' - -on: - push: - branches: - - master - paths-ignore: - - '**/*.md' - pull_request: - branches: - - master - paths-ignore: - - '**/*.md' - workflow_dispatch: - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/build.yaml@master diff --git a/.github/workflows/changelog.yaml b/.github/workflows/changelog.yaml deleted file mode 100644 index 5b3c3be..0000000 --- a/.github/workflows/changelog.yaml +++ /dev/null @@ -1,20 +0,0 @@ -name: '๐Ÿ“ Create/Update Release Draft & Release Bump PR' - -on: - push: - branches: - - master - paths-ignore: - - build.yaml - workflow_dispatch: - repository_dispatch: - types: - - update-prep-command - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/changelog.yaml@master - with: - repository-name: jellyfin/jellyfin-plugin-template - secrets: - token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/command-dispatch.yaml b/.github/workflows/command-dispatch.yaml deleted file mode 100644 index 1b5e4ee..0000000 --- a/.github/workflows/command-dispatch.yaml +++ /dev/null @@ -1,13 +0,0 @@ -# Allows for the definition of PR and Issue /commands -name: '๐Ÿ“Ÿ Slash Command Dispatcher' - -on: - issue_comment: - types: - - created - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/command-dispatch.yaml@master - secrets: - token: . diff --git a/.github/workflows/command-rebase.yaml b/.github/workflows/command-rebase.yaml deleted file mode 100644 index 7847e20..0000000 --- a/.github/workflows/command-rebase.yaml +++ /dev/null @@ -1,16 +0,0 @@ -name: '๐Ÿ”€ PR Rebase Command' - -on: - repository_dispatch: - types: - - rebase-command - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/command-rebase.yaml@master - with: - rebase-head: ${{ github.event.client_payload.pull_request.head.label }} - repository-full-name: ${{ github.event.client_payload.github.payload.repository.full_name }} - comment-id: ${{ github.event.client_payload.github.payload.comment.id }} - secrets: - token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml deleted file mode 100644 index 80483cf..0000000 --- a/.github/workflows/publish.yaml +++ /dev/null @@ -1,18 +0,0 @@ -name: '๐Ÿš€ Publish Plugin' - -on: - release: - types: - - released - workflow_dispatch: - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/publish.yaml@master - with: - version: ${{ github.event.release.tag_name }} - is-unstable: ${{ github.event.release.prerelease }} - secrets: - deploy-host: ${{ secrets.DEPLOY_HOST }} - deploy-user: ${{ secrets.DEPLOY_USER }} - deploy-key: ${{ secrets.DEPLOY_KEY }} diff --git a/.github/workflows/scan-codeql.yaml b/.github/workflows/scan-codeql.yaml deleted file mode 100644 index ca8b0b0..0000000 --- a/.github/workflows/scan-codeql.yaml +++ /dev/null @@ -1,20 +0,0 @@ -name: '๐Ÿ”ฌ Run CodeQL' - -on: - push: - branches: [ master ] - paths-ignore: - - '**/*.md' - pull_request: - branches: [ master ] - paths-ignore: - - '**/*.md' - schedule: - - cron: '24 2 * * 4' - workflow_dispatch: - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/scan-codeql.yaml@master - with: - repository-name: jellyfin/jellyfin-plugin-template diff --git a/.github/workflows/sync-labels.yaml b/.github/workflows/sync-labels.yaml deleted file mode 100644 index 5e06ae4..0000000 --- a/.github/workflows/sync-labels.yaml +++ /dev/null @@ -1,12 +0,0 @@ -name: '๐Ÿท๏ธ Sync labels' - -on: - schedule: - - cron: '0 0 1 * *' - workflow_dispatch: - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/sync-labels.yaml@master - secrets: - token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml deleted file mode 100644 index d90b14d..0000000 --- a/.github/workflows/test.yaml +++ /dev/null @@ -1,18 +0,0 @@ -name: '๐Ÿงช Test Plugin' - -on: - push: - branches: - - master - paths-ignore: - - '**/*.md' - pull_request: - branches: - - master - paths-ignore: - - '**/*.md' - workflow_dispatch: - -jobs: - call: - uses: jellyfin/jellyfin-meta-plugins/.github/workflows/test.yaml@master diff --git a/.gitignore b/.gitignore index 0b72c24..aca29f0 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ obj/ .vs/ .idea/ artifacts +spec.md diff --git a/Dockerfile.builder b/Dockerfile.builder new file mode 100644 index 0000000..f1bb8dd --- /dev/null +++ b/Dockerfile.builder @@ -0,0 +1,18 @@ +# Watched Together builder image +# Pre-built image with the .NET 9 SDK and JPRM for building and testing the plugin. +# Build: docker build -f Dockerfile.builder -t gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest . +# Push: docker push gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest + +FROM mcr.microsoft.com/dotnet/sdk:9.0 + +RUN apt-get update && apt-get install -y \ + python3 \ + python3-pip \ + git \ + jq \ + curl \ + && rm -rf /var/lib/apt/lists/* + +RUN pip install --break-system-packages jprm + +WORKDIR /src diff --git a/Jellyfin.Plugin.Template.sln b/Jellyfin.Plugin.Template.sln deleted file mode 100644 index 7c9b9ee..0000000 --- a/Jellyfin.Plugin.Template.sln +++ /dev/null @@ -1,28 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.Template", "Jellyfin.Plugin.Template\Jellyfin.Plugin.Template.csproj", "{D921B930-CF91-406F-ACBC-08914DCD0D34}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x64.ActiveCfg = Debug|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x64.Build.0 = Debug|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x86.ActiveCfg = Debug|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x86.Build.0 = Debug|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.Build.0 = Release|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x64.ActiveCfg = Release|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x64.Build.0 = Release|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x86.ActiveCfg = Release|Any CPU - {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/Jellyfin.Plugin.Template/Configuration/PluginConfiguration.cs b/Jellyfin.Plugin.Template/Configuration/PluginConfiguration.cs deleted file mode 100644 index 564e6bf..0000000 --- a/Jellyfin.Plugin.Template/Configuration/PluginConfiguration.cs +++ /dev/null @@ -1,57 +0,0 @@ -using MediaBrowser.Model.Plugins; - -namespace Jellyfin.Plugin.Template.Configuration; - -/// -/// The configuration options. -/// -public enum SomeOptions -{ - /// - /// Option one. - /// - OneOption, - - /// - /// Second option. - /// - AnotherOption -} - -/// -/// Plugin configuration. -/// -public class PluginConfiguration : BasePluginConfiguration -{ - /// - /// Initializes a new instance of the class. - /// - public PluginConfiguration() - { - // set default options here - Options = SomeOptions.AnotherOption; - TrueFalseSetting = true; - AnInteger = 2; - AString = "string"; - } - - /// - /// Gets or sets a value indicating whether some true or false setting is enabled.. - /// - public bool TrueFalseSetting { get; set; } - - /// - /// Gets or sets an integer setting. - /// - public int AnInteger { get; set; } - - /// - /// Gets or sets a string setting. - /// - public string AString { get; set; } - - /// - /// Gets or sets an enum option. - /// - public SomeOptions Options { get; set; } -} diff --git a/Jellyfin.Plugin.Template/Configuration/configPage.html b/Jellyfin.Plugin.Template/Configuration/configPage.html deleted file mode 100644 index 23f024e..0000000 --- a/Jellyfin.Plugin.Template/Configuration/configPage.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - Template - - -
-
-
-
-
- - -
-
- - -
A Description
-
-
- -
-
- - -
Another Description
-
-
- -
-
-
-
- -
- - diff --git a/Jellyfin.Plugin.WatchedTogether.Tests/AuthenticationTests.cs b/Jellyfin.Plugin.WatchedTogether.Tests/AuthenticationTests.cs new file mode 100644 index 0000000..a48d626 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.Tests/AuthenticationTests.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Plugin.WatchedTogether.Auth; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using Jellyfin.Plugin.WatchedTogether.Services; +using MediaBrowser.Controller.Authentication; +using MediaBrowser.Model.Cryptography; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Plugin.WatchedTogether.Tests; + +/// +/// Covers the rule that makes this plugin work: any member's password unlocks the shared account, +/// and nothing else does. +/// +public class AuthenticationTests +{ + // PasswordHash.Parse requires hex-encoded salt and hash segments, so these fixtures use real + // hex rather than readable placeholders. + private const string AliceHash = "$PBKDF2-SHA512$iterations=210000$A1A1A1A1$AAAAAAAABBBBBBBB"; + private const string BobHash = "$PBKDF2-SHA512$iterations=210000$B2B2B2B2$CCCCCCCCDDDDDDDD"; + + private static User MakeUser(string name, string? password) + { + var user = new User(name, "Prov", "ResetProv") { Password = password! }; + return user; + } + + /// + /// Builds a provider whose crypto accepts exactly the (hash, password) pairs given. + /// + private static SharedAccountAuthenticationProvider MakeProvider( + SharedGroup? group, + IReadOnlyList members, + params (string Hash, string Password)[] validPairs) + => MakeProvider(group, members, null, validPairs); + + /// + /// Builds a provider, optionally with a dynamic-group service that returns + /// for an unresolved username. + /// + private static SharedAccountAuthenticationProvider MakeProvider( + SharedGroup? group, + IReadOnlyList members, + DynamicGroupResult? dynamicResult, + params (string Hash, string Password)[] validPairs) + { + // ICryptoProvider.Verify takes a ReadOnlySpan, which Moq cannot express as a generic + // argument, so the crypto provider is stubbed by hand. + var crypto = new StubCryptoProvider(validPairs); + + var groups = new Mock(); + groups.Setup(g => g.GetGroupForSharedUser(It.IsAny())).Returns(group); + groups.Setup(g => g.GetEligibleMembers(It.IsAny())).Returns(members); + + var dynamic = new Mock(); + dynamic.Setup(d => d.TryCreateFromLoginAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(dynamicResult); + + return new SharedAccountAuthenticationProvider( + crypto, + groups.Object, + dynamic.Object, + NullLogger.Instance); + } + + [Fact] + public async Task Authenticate_WithFirstMemberPassword_Succeeds() + { + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var shared = MakeUser("alice+bob", null); + var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] }; + + var provider = MakeProvider(group, [alice, bob], (AliceHash, "alice-pw")); + + var result = await provider.Authenticate("alice+bob", "alice-pw", shared); + + Assert.Equal("alice+bob", result.Username); + } + + [Fact] + public async Task Authenticate_WithLaterMemberPassword_Succeeds() + { + // The second member's password must work even though the first member's check failed + // first - that loop is the whole point of the plugin. + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var shared = MakeUser("alice+bob", null); + var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] }; + + var provider = MakeProvider(group, [alice, bob], (BobHash, "bob-pw")); + + var result = await provider.Authenticate("alice+bob", "bob-pw", shared); + + Assert.Equal("alice+bob", result.Username); + } + + [Fact] + public async Task Authenticate_WithWrongPassword_Throws() + { + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var shared = MakeUser("alice+bob", null); + var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] }; + + var provider = MakeProvider(group, [alice, bob], (AliceHash, "alice-pw")); + + await Assert.ThrowsAsync( + () => provider.Authenticate("alice+bob", "not-the-password", shared)); + } + + [Fact] + public async Task Authenticate_WhenGroupDisabledOrUnknown_Throws() + { + // GetGroupForSharedUser returns null both for accounts we do not manage and for groups an + // admin has suspended. Neither may be unlocked. + var shared = MakeUser("alice+bob", null); + var provider = MakeProvider(null, [], (AliceHash, "alice-pw")); + + await Assert.ThrowsAsync( + () => provider.Authenticate("alice+bob", "alice-pw", shared)); + } + + [Fact] + public async Task Authenticate_WhenNoEligibleMembers_Throws() + { + // Every member disabled or deleted: a correct password for a now-disabled member must not + // still open the account. + var shared = MakeUser("alice+bob", null); + var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [Guid.NewGuid()] }; + + var provider = MakeProvider(group, [], (AliceHash, "alice-pw")); + + await Assert.ThrowsAsync( + () => provider.Authenticate("alice+bob", "alice-pw", shared)); + } + + [Fact] + public async Task Authenticate_MemberWithNoPassword_IsSkipped() + { + // A passwordless member contributes no credential; an empty submitted password must not + // match them and unlock the account. + var ghost = MakeUser("ghost", null); + var bob = MakeUser("bob", BobHash); + var shared = MakeUser("ghost+bob", null); + var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [ghost.Id, bob.Id] }; + + var provider = MakeProvider(group, [ghost, bob], (BobHash, "bob-pw")); + + await Assert.ThrowsAsync( + () => provider.Authenticate("ghost+bob", string.Empty, shared)); + } + + [Fact] + public async Task Authenticate_WithNullResolvedUser_AndNoDynamicMatch_Throws() + { + // Nothing resolved and the name is not a valid member combination. + var provider = MakeProvider(null, [], dynamicResult: null, (AliceHash, "alice-pw")); + + await Assert.ThrowsAsync( + () => provider.Authenticate("whoever", "alice-pw", null)); + } + + [Fact] + public async Task Authenticate_WithNullResolvedUser_CreatesGroupOnDemand() + { + // Typing "alice+bob" with a member's password provisions the shared account and logs in. + var group = new SharedGroup { SharedUserId = Guid.NewGuid() }; + var provider = MakeProvider( + null, + [], + new DynamicGroupResult(group, "alice+bob"), + (AliceHash, "alice-pw")); + + var result = await provider.Authenticate("alice+bob", "alice-pw", null); + + Assert.Equal("alice+bob", result.Username); + } + + [Fact] + public async Task Authenticate_TwoArgOverload_AlsoCreatesGroupOnDemand() + { + // The two-argument overload is equivalent to passing a null resolved user. + var group = new SharedGroup { SharedUserId = Guid.NewGuid() }; + var provider = MakeProvider( + null, + [], + new DynamicGroupResult(group, "alice+bob"), + (AliceHash, "alice-pw")); + + var result = await provider.Authenticate("alice+bob", "alice-pw"); + + Assert.Equal("alice+bob", result.Username); + } + + [Fact] + public void HasPassword_IsAlwaysTrue() + { + // Returning false would let a client offer a passwordless login for the shared account. + var provider = MakeProvider(null, []); + Assert.True(provider.HasPassword(MakeUser("alice+bob", null))); + } + + [Fact] + public async Task ChangePassword_IsNotSupported() + { + var provider = MakeProvider(null, []); + await Assert.ThrowsAsync( + () => provider.ChangePassword(MakeUser("alice+bob", null), "new-pw")); + } +} diff --git a/Jellyfin.Plugin.WatchedTogether.Tests/DynamicGroupTests.cs b/Jellyfin.Plugin.WatchedTogether.Tests/DynamicGroupTests.cs new file mode 100644 index 0000000..e41d83c --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.Tests/DynamicGroupTests.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Jellyfin.Data; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Enums; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using Jellyfin.Plugin.WatchedTogether.Services; +using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Plugin.WatchedTogether.Tests; + +/// +/// Covers creating a shared account on the fly from a name typed at the login screen. +/// +/// +/// These tests drive through a stubbed user manager. They rely on +/// configuration, which is set up per test via +/// . +/// +[Collection(nameof(PluginTestContext))] +public class DynamicGroupTests +{ + private const string AliceHash = "$PBKDF2-SHA512$iterations=210000$A1A1A1A1$AAAAAAAABBBBBBBB"; + private const string BobHash = "$PBKDF2-SHA512$iterations=210000$B2B2B2B2$CCCCCCCCDDDDDDDD"; + + private static User MakeUser(string name, string? password = null, bool disabled = false) + { + var user = new User(name, "Prov", "ResetProv"); + if (password is not null) + { + user.Password = password; + } + + if (disabled) + { + user.SetPermission(PermissionKind.IsDisabled, true); + } + + return user; + } + + private sealed record Harness( + DynamicGroupService Service, + Mock Provisioning); + + private static Harness MakeService( + IReadOnlyList knownUsers, + params (string Hash, string Password)[] validPairs) + { + var userManager = new Mock(); + + userManager.Setup(m => m.GetUserByName(It.IsAny())) + .Returns((string n) => + { + foreach (var u in knownUsers) + { + if (string.Equals(u.Username, n, StringComparison.OrdinalIgnoreCase)) + { + return u; + } + } + + return null!; + }); + + var provisioning = new Mock(); + var createdShared = MakeUser("created-shared"); + + provisioning.Setup(p => p.CreateGroupAsync( + It.IsAny>(), + It.IsAny(), + It.IsAny(), + It.IsAny?>())) + .ReturnsAsync((IReadOnlyList ids, string? name, bool _, IReadOnlyList? _) => + new SharedGroup { SharedUserId = createdShared.Id, MemberUserIds = [.. ids] }); + + userManager.Setup(m => m.GetUserById(createdShared.Id)).Returns(createdShared); + + var service = new DynamicGroupService( + userManager.Object, + provisioning.Object, + new StubCryptoProvider(validPairs), + NullLogger.Instance); + + return new Harness(service, provisioning); + } + + [Fact] + public async Task TypingTwoMemberNames_WithAMemberPassword_CreatesTheAccount() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var h = MakeService([alice, bob], (AliceHash, "alice-pw")); + + var result = await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw"); + + Assert.NotNull(result); + h.Provisioning.Verify( + p => p.CreateGroupAsync( + It.Is>(ids => ids.Count == 2), + "alice+bob", + It.IsAny(), + It.IsAny?>()), + Times.Once); + } + + [Fact] + public async Task AnyNamedMembersPassword_Works() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var h = MakeService([alice, bob], (BobHash, "bob-pw")); + + Assert.NotNull(await h.Service.TryCreateFromLoginAsync("alice+bob", "bob-pw")); + } + + [Fact] + public async Task WithoutAMatchingPassword_NothingIsCreated() + { + // Otherwise anyone who knows two usernames could conjure a shared account into existence. + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var h = MakeService([alice, bob], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "guessing")); + h.Provisioning.VerifyNoOtherCalls(); + } + + [Fact] + public async Task AnUnknownNamePart_IsRejected() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var h = MakeService([alice], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+nobody", "alice-pw")); + h.Provisioning.VerifyNoOtherCalls(); + } + + [Fact] + public async Task ADisabledMember_IsRejected() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash, disabled: true); + var h = MakeService([alice, bob], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw")); + } + + [Fact] + public async Task ASingleName_IsNotAGroup() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var h = MakeService([alice], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice", "alice-pw")); + } + + [Fact] + public async Task TheSameMemberTwice_IsRejected() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var h = MakeService([alice], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+alice", "alice-pw")); + } + + [Fact] + public async Task AnExistingSharedAccountNamedPart_IsRejected() + { + // Shared accounts must not nest inside other shared accounts. + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var existingShared = MakeUser("shared", BobHash); + ctx.Configuration.Groups.Add(new SharedGroup { SharedUserId = existingShared.Id }); + + var h = MakeService([alice, existingShared], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+shared", "alice-pw")); + } + + [Fact] + public async Task WhenDisabledInConfiguration_NothingIsCreated() + { + using var ctx = PluginTestContext.Create(); + ctx.Configuration.EnableDynamicGroups = false; + + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var h = MakeService([alice, bob], (AliceHash, "alice-pw")); + + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw")); + } + + [Fact] + public async Task AConfiguredSeparator_IsHonoured() + { + using var ctx = PluginTestContext.Create(); + ctx.Configuration.NameSeparator = "_"; + + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var h = MakeService([alice, bob], (AliceHash, "alice-pw")); + + Assert.NotNull(await h.Service.TryCreateFromLoginAsync("alice_bob", "alice-pw")); + Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw")); + } + + [Fact] + public async Task ThreeOrMoreMembers_AreSupported() + { + using var ctx = PluginTestContext.Create(); + var alice = MakeUser("alice", AliceHash); + var bob = MakeUser("bob", BobHash); + var carol = MakeUser("carol", BobHash); + var h = MakeService([alice, bob, carol], (AliceHash, "alice-pw")); + + Assert.NotNull(await h.Service.TryCreateFromLoginAsync("alice+bob+carol", "alice-pw")); + h.Provisioning.Verify( + p => p.CreateGroupAsync( + It.Is>(ids => ids.Count == 3), + It.IsAny(), + It.IsAny(), + It.IsAny?>()), + Times.Once); + } +} diff --git a/Jellyfin.Plugin.WatchedTogether.Tests/Jellyfin.Plugin.WatchedTogether.Tests.csproj b/Jellyfin.Plugin.WatchedTogether.Tests/Jellyfin.Plugin.WatchedTogether.Tests.csproj new file mode 100644 index 0000000..ad25d5a --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.Tests/Jellyfin.Plugin.WatchedTogether.Tests.csproj @@ -0,0 +1,41 @@ + + + + net9.0 + enable + false + + false + Default + false + $(NoWarn);CA1707;SA0001;CS1591 + + LatestMajor + + + + + + + + + + + + + + + + + + + + diff --git a/Jellyfin.Plugin.WatchedTogether.Tests/PluginTestContext.cs b/Jellyfin.Plugin.WatchedTogether.Tests/PluginTestContext.cs new file mode 100644 index 0000000..4e27620 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.Tests/PluginTestContext.cs @@ -0,0 +1,74 @@ +using System; +using System.IO; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Model.Serialization; +using Moq; +using Xunit; + +namespace Jellyfin.Plugin.WatchedTogether.Tests; + +/// +/// Marks tests that read or write the process-wide , so xUnit runs +/// them serially rather than letting parallel classes clobber each other's configuration. +/// +[CollectionDefinition(nameof(PluginTestContext))] +public class PluginTestCollection : ICollectionFixture +{ +} + +/// +/// Constructs a real backed by a temporary directory so that services reading +/// have configuration to work with, and cleans up afterwards. +/// +public sealed class PluginTestContext : IDisposable +{ + private readonly string _configDirectory; + + private PluginTestContext(Plugin plugin, string configDirectory) + { + Plugin = plugin; + _configDirectory = configDirectory; + } + + public Plugin Plugin { get; } + + public PluginConfiguration Configuration => Plugin.Configuration; + + public static PluginTestContext Create() + { + var dir = Path.Combine(Path.GetTempPath(), "wt-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + + // BasePlugin derives its data folder from PluginsPath and its config file from + // PluginConfigurationsPath, so both must resolve to a real directory. + var paths = new Mock(); + paths.SetupGet(p => p.PluginConfigurationsPath).Returns(dir); + paths.SetupGet(p => p.PluginsPath).Returns(dir); + + // BasePlugin persists configuration through the serializer; a stub keeps tests off disk + // while still letting UpdateConfiguration succeed. + var serializer = new Mock(); + serializer.Setup(s => s.DeserializeFromFile(It.IsAny(), It.IsAny())) + .Returns(new PluginConfiguration()); + + var plugin = new Plugin(paths.Object, serializer.Object); + + return new PluginTestContext(plugin, dir); + } + + public void Dispose() + { + try + { + if (Directory.Exists(_configDirectory)) + { + Directory.Delete(_configDirectory, recursive: true); + } + } + catch (IOException) + { + // A leftover temp directory is not worth failing a test over. + } + } +} diff --git a/Jellyfin.Plugin.WatchedTogether.Tests/StubCryptoProvider.cs b/Jellyfin.Plugin.WatchedTogether.Tests/StubCryptoProvider.cs new file mode 100644 index 0000000..8250f74 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.Tests/StubCryptoProvider.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using MediaBrowser.Model.Cryptography; + +namespace Jellyfin.Plugin.WatchedTogether.Tests; + +/// +/// A crypto provider that accepts exactly the (stored hash, submitted password) pairs it is given. +/// +/// +/// Hand-written rather than mocked: takes a +/// ReadOnlySpan<char>, and a ref struct cannot be used as a generic type argument to +/// Moq's It.IsAny<T>. +/// +public sealed class StubCryptoProvider : ICryptoProvider +{ + private readonly IReadOnlyList<(string Hash, string Password)> _validPairs; + + public StubCryptoProvider(IReadOnlyList<(string Hash, string Password)> validPairs) + { + _validPairs = validPairs; + } + + public string DefaultHashMethod => "PBKDF2-SHA512"; + + public bool Verify(PasswordHash hash, ReadOnlySpan password) + { + var candidate = password.ToString(); + + // Identify the stored credential by its salt rather than by re-formatting the whole hash, + // which need not round-trip through Parse/ToString byte for byte. + var salt = Convert.ToHexString(hash.Salt); + + foreach (var (validHash, validPassword) in _validPairs) + { + var expectedSalt = validHash.Split('$')[3]; + if (string.Equals(salt, expectedSalt, StringComparison.OrdinalIgnoreCase) + && candidate == validPassword) + { + return true; + } + } + + return false; + } + + public PasswordHash CreatePasswordHash(ReadOnlySpan password) + => throw new NotSupportedException(); + + public byte[] GenerateSalt() => throw new NotSupportedException(); + + public byte[] GenerateSalt(int length) => throw new NotSupportedException(); +} diff --git a/Jellyfin.Plugin.WatchedTogether.Tests/WatchedStateSyncTests.cs b/Jellyfin.Plugin.WatchedTogether.Tests/WatchedStateSyncTests.cs new file mode 100644 index 0000000..e6589ec --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.Tests/WatchedStateSyncTests.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using Jellyfin.Plugin.WatchedTogether.Services; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Entities; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Plugin.WatchedTogether.Tests; + +/// +/// Covers propagation of played state from a shared account to its members. +/// +public class WatchedStateSyncTests +{ + private static readonly Guid SharedId = Guid.NewGuid(); + + private sealed class Harness + { + public Mock UserData { get; } = new(); + + public Mock Groups { get; } = new(); + + public List<(User Member, bool Played, int PlayCount)> Saves { get; } = new(); + + public WatchedStateSyncService Service { get; private set; } = null!; + + public static Harness Create( + SharedGroup? group, + IReadOnlyList members, + bool memberAlreadyPlayed = false, + int memberPlayCount = 0) + { + var h = new Harness(); + + h.Groups.Setup(g => g.GetGroupForSharedUser(It.IsAny())).Returns(group); + h.Groups.Setup(g => g.GetEligibleMembers(It.IsAny())).Returns(members); + + h.UserData.Setup(m => m.GetUserData(It.IsAny(), It.IsAny())) + .Returns(() => new UserItemData + { + Key = "k", + Played = memberAlreadyPlayed, + PlayCount = memberPlayCount + }); + + h.UserData.Setup(m => m.SaveUserData( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny())) + .Callback( + (u, _, d, _, _) => h.Saves.Add((u, d.Played, d.PlayCount))); + + h.Service = new WatchedStateSyncService( + h.UserData.Object, + new Mock().Object, + h.Groups.Object, + NullLogger.Instance); + + return h; + } + + /// + /// Raises UserDataSaved as the server would, by starting the service so it subscribes. + /// + public void Raise(Guid userId, bool played, UserDataSaveReason reason) + { + Service.StartAsync(CancellationToken.None).GetAwaiter().GetResult(); + + UserData.Raise( + m => m.UserDataSaved += null, + new UserDataSaveEventArgs + { + UserId = userId, + Item = new Folder { Name = "Some Item" }, + UserData = new UserItemData { Key = "k", Played = played }, + SaveReason = reason + }); + + Service.StopAsync(CancellationToken.None).GetAwaiter().GetResult(); + } + } + + private static User MakeUser(string name) => new(name, "Prov", "ResetProv"); + + private static SharedGroup MakeGroup(bool syncUnwatched = true, bool syncPlayCount = false) + => new() + { + SharedUserId = SharedId, + MemberUserIds = [Guid.NewGuid(), Guid.NewGuid()], + SyncUnwatched = syncUnwatched, + SyncPlayCount = syncPlayCount + }; + + [Fact] + public void Played_PropagatesToEveryMember() + { + var alice = MakeUser("alice"); + var bob = MakeUser("bob"); + var h = Harness.Create(MakeGroup(), [alice, bob]); + + h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished); + + Assert.Equal(2, h.Saves.Count); + Assert.All(h.Saves, s => Assert.True(s.Played)); + } + + [Fact] + public void WritesFromAMember_AreIgnored() + { + // The loop guard: a member's own save must not be treated as a shared-account change. + // GetGroupForSharedUser returns null for any id that is not a shared account. + var h = Harness.Create(null, []); + + h.Raise(Guid.NewGuid(), true, UserDataSaveReason.PlaybackFinished); + + Assert.Empty(h.Saves); + } + + [Theory] + [InlineData(UserDataSaveReason.PlaybackStart)] + [InlineData(UserDataSaveReason.PlaybackProgress)] + [InlineData(UserDataSaveReason.UpdateUserRating)] + public void IrrelevantSaveReasons_AreIgnored(UserDataSaveReason reason) + { + // UserDataSaved fires constantly during playback; only watched-state changes matter. + var h = Harness.Create(MakeGroup(), [MakeUser("alice")]); + + h.Raise(SharedId, true, reason); + + Assert.Empty(h.Saves); + } + + [Fact] + public void Unwatched_PropagatesWhenSyncUnwatchedEnabled() + { + var h = Harness.Create(MakeGroup(syncUnwatched: true), [MakeUser("alice")], memberAlreadyPlayed: true); + + h.Raise(SharedId, false, UserDataSaveReason.TogglePlayed); + + Assert.Single(h.Saves); + Assert.False(h.Saves[0].Played); + } + + [Fact] + public void Unwatched_IsSuppressedWhenSyncUnwatchedDisabled() + { + var h = Harness.Create(MakeGroup(syncUnwatched: false), [MakeUser("alice")], memberAlreadyPlayed: true); + + h.Raise(SharedId, false, UserDataSaveReason.TogglePlayed); + + Assert.Empty(h.Saves); + } + + [Fact] + public void RedundantWrites_AreSuppressed() + { + // The member already matches the shared account, so there is nothing to write. + var h = Harness.Create(MakeGroup(), [MakeUser("alice")], memberAlreadyPlayed: true); + + h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished); + + Assert.Empty(h.Saves); + } + + [Fact] + public void PlayCount_IsRaisedWhenEnabled() + { + var h = Harness.Create(MakeGroup(syncPlayCount: true), [MakeUser("alice")]); + + h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished); + + Assert.Single(h.Saves); + Assert.Equal(1, h.Saves[0].PlayCount); + } + + [Fact] + public void PlayCount_IsNotDecrementedForAlreadyWatchedItems() + { + // A member who has watched something five times keeps that count. + var h = Harness.Create( + MakeGroup(syncPlayCount: true), + [MakeUser("alice")], + memberAlreadyPlayed: false, + memberPlayCount: 5); + + h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished); + + Assert.Single(h.Saves); + Assert.Equal(5, h.Saves[0].PlayCount); + } + + [Fact] + public void PlayCount_IsLeftAloneWhenDisabled() + { + var h = Harness.Create(MakeGroup(syncPlayCount: false), [MakeUser("alice")]); + + h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished); + + Assert.Single(h.Saves); + Assert.Equal(0, h.Saves[0].PlayCount); + } + + [Fact] + public void DisabledGroup_DoesNotSync() + { + // GetGroupForSharedUser returns null for suspended groups. + var h = Harness.Create(null, [MakeUser("alice")]); + + h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished); + + Assert.Empty(h.Saves); + } +} diff --git a/Jellyfin.Plugin.WatchedTogether.sln b/Jellyfin.Plugin.WatchedTogether.sln new file mode 100644 index 0000000..c6764a7 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether.sln @@ -0,0 +1,42 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.WatchedTogether", "Jellyfin.Plugin.WatchedTogether\Jellyfin.Plugin.WatchedTogether.csproj", "{D921B930-CF91-406F-ACBC-08914DCD0D34}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.WatchedTogether.Tests", "Jellyfin.Plugin.WatchedTogether.Tests\\Jellyfin.Plugin.WatchedTogether.Tests.csproj", "{E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x64.ActiveCfg = Debug|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x64.Build.0 = Debug|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x86.ActiveCfg = Debug|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x86.Build.0 = Debug|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.Build.0 = Release|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x64.ActiveCfg = Release|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x64.Build.0 = Release|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x86.ActiveCfg = Release|Any CPU + {D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x86.Build.0 = Release|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Debug|x64.ActiveCfg = Debug|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Debug|x64.Build.0 = Debug|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Debug|x86.ActiveCfg = Debug|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Debug|x86.Build.0 = Debug|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Release|Any CPU.Build.0 = Release|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Release|x64.ActiveCfg = Release|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Release|x64.Build.0 = Release|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Release|x86.ActiveCfg = Release|Any CPU + {E1B2C3D4-5F60-4A7B-8C9D-0E1F2A3B4C5D}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/Jellyfin.Plugin.WatchedTogether/Auth/SharedAccountAuthenticationProvider.cs b/Jellyfin.Plugin.WatchedTogether/Auth/SharedAccountAuthenticationProvider.cs new file mode 100644 index 0000000..37d535d --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Auth/SharedAccountAuthenticationProvider.cs @@ -0,0 +1,179 @@ +using System; +using System.Threading.Tasks; +using Jellyfin.Database.Implementations.Entities; +using MediaBrowser.Controller.Authentication; +using MediaBrowser.Model.Cryptography; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Auth; + +/// +/// Authenticates a shared account against the passwords of each of its members. +/// +/// +/// +/// Jellyfin selects a provider per user via User.AuthenticationProviderId, so this provider +/// only ever sees shared accounts that provisioning assigned to it. Implementing +/// means Jellyfin hands us the already-resolved shared account +/// rather than us having to look it up by name. +/// +/// +/// Verification reads each member's stored hash directly instead of calling +/// IUserManager.AuthenticateUser. Going through the normal flow would trip every member's +/// failed-attempt counter each time a different member's password was the one that +/// matched, eventually locking out members who did nothing wrong. Reading the live hash also means +/// member password changes take effect immediately, with no second copy of any credential stored. +/// +/// +public class SharedAccountAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser +{ + private readonly ICryptoProvider _cryptoProvider; + private readonly Services.IGroupService _groupService; + private readonly Services.IDynamicGroupService _dynamicGroupService; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The crypto provider used to verify stored password hashes. + /// The group service. + /// The on-demand group creation service. + /// The logger. + public SharedAccountAuthenticationProvider( + ICryptoProvider cryptoProvider, + Services.IGroupService groupService, + Services.IDynamicGroupService dynamicGroupService, + ILogger logger) + { + _cryptoProvider = cryptoProvider; + _groupService = groupService; + _dynamicGroupService = dynamicGroupService; + _logger = logger; + } + + /// + public string Name => "Watched Together Shared Account"; + + /// + public bool IsEnabled => true; + + /// + /// + /// Jellyfin calls the overload instead, so this exists only + /// to satisfy the interface. + /// + public Task Authenticate(string username, string password) + => Authenticate(username, password, null); + + /// + public async Task Authenticate(string username, string password, User? resolvedUser) + { + // Jellyfin passes a null user when no account matches the typed name, and offers the login + // to every enabled provider. That is the hook for "type alice+bob and the account appears": + // a real user with that exact name always resolves first and never reaches this branch. + if (resolvedUser is null) + { + var created = await _dynamicGroupService + .TryCreateFromLoginAsync(username, password) + .ConfigureAwait(false); + + if (created is null) + { + throw new AuthenticationException("Invalid username or password."); + } + + return new ProviderAuthenticationResult { Username = created.SharedUsername }; + } + + var group = _groupService.GetGroupForSharedUser(resolvedUser.Id); + if (group is null) + { + // Either not one of ours, or the group is disabled. Either way this account has no + // member passwords to check, so it cannot be unlocked. + _logger.LogWarning( + "Rejected login for {Username}: no enabled Watched Together group owns this account", + resolvedUser.Username); + throw new AuthenticationException("Invalid username or password."); + } + + var members = _groupService.GetEligibleMembers(group); + if (members.Count == 0) + { + _logger.LogWarning( + "Rejected login for {Username}: group has no eligible members", + resolvedUser.Username); + throw new AuthenticationException("Invalid username or password."); + } + + foreach (var member in members) + { + if (!VerifyPassword(member, password)) + { + continue; + } + + _logger.LogInformation( + "Shared account {SharedUsername} unlocked by member {MemberUsername}", + resolvedUser.Username, + member.Username); + + return new ProviderAuthenticationResult + { + Username = resolvedUser.Username + }; + } + + _logger.LogWarning( + "Rejected login for {Username}: no member password matched", + resolvedUser.Username); + throw new AuthenticationException("Invalid username or password."); + } + + /// + /// + /// A shared account always has a password in the sense that matters to Jellyfin: some member + /// credential is required. Returning false would let clients offer a passwordless login. + /// + public bool HasPassword(User user) => true; + + /// + /// + /// Shared accounts have no password of their own to change - members change their own passwords + /// in the normal way and the effect is picked up on the next login. + /// + public Task ChangePassword(User user, string newPassword) + { + throw new NotSupportedException( + "A Watched Together shared account has no password of its own. Members change their own passwords instead."); + } + + /// + /// Verifies a submitted password against a member's live stored hash. + /// + /// The member whose stored credential to check. + /// The submitted password. + /// true if the password matches. + private bool VerifyPassword(User member, string password) + { + if (string.IsNullOrEmpty(member.Password)) + { + // A member with no password set cannot contribute a credential to the group. + return false; + } + + try + { + var hash = PasswordHash.Parse(member.Password); + return _cryptoProvider.Verify(hash, password); + } + catch (Exception ex) when (ex is FormatException or ArgumentException) + { + // Never log the hash or the submitted password. + _logger.LogError( + ex, + "Could not parse the stored password hash for member {MemberId}; skipping", + member.Id); + return false; + } + } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Configuration/PluginConfiguration.cs b/Jellyfin.Plugin.WatchedTogether/Configuration/PluginConfiguration.cs new file mode 100644 index 0000000..39bf4f8 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Configuration/PluginConfiguration.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using MediaBrowser.Model.Plugins; + +namespace Jellyfin.Plugin.WatchedTogether.Configuration; + +/// +/// Plugin configuration. Holds the authoritative record of which members belong to which +/// shared account. +/// +public class PluginConfiguration : BasePluginConfiguration +{ + /// + /// Gets or sets the configured shared-account groups. + /// + [SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List.")] + [SuppressMessage("Design", "CA1002:Do not expose generic lists", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List.")] + public List Groups { get; set; } = new(); + + /// + /// Gets or sets the separator used to join member names into a shared account name. Also the + /// separator split at login when is on. + /// + public string NameSeparator { get; set; } = "+"; + + /// + /// Gets or sets a value indicating whether typing an unrecognised name like "alice+bob" at the + /// login screen creates the shared account on the spot. + /// + /// + /// The account is only created if every named part is an existing, enabled, non-shared user + /// and the submitted password belongs to one of them. A real account whose name + /// happens to contain the separator always takes precedence, because Jellyfin only consults + /// this plugin once no local user matches the typed name. + /// + public bool EnableDynamicGroups { get; set; } = true; + + /// + /// Gets or sets a value indicating whether accounts created on demand may access all libraries. + /// + /// + /// Leaving this on means a dynamically created account sees every library, regardless of what + /// its members can each reach individually. Turn it off to have such accounts start with no + /// library access until an administrator grants it. + /// + public bool DynamicGroupsEnableAllFolders { get; set; } = true; +} diff --git a/Jellyfin.Plugin.WatchedTogether/Configuration/SharedGroup.cs b/Jellyfin.Plugin.WatchedTogether/Configuration/SharedGroup.cs new file mode 100644 index 0000000..0dfc43e --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Configuration/SharedGroup.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Jellyfin.Plugin.WatchedTogether.Configuration; + +/// +/// The association between one shared account and the members who may unlock it. +/// +/// +/// Membership is stored as GUIDs rather than being parsed out of the shared account's username. +/// The default separator ('+') is itself a legal username character, so a name like "alice+bob" +/// is ambiguous between the group [alice, bob] and a single user literally called "alice+bob". +/// GUIDs remove that ambiguity and support any number of members. +/// +public class SharedGroup +{ + /// + /// Gets or sets the identifier of the shared account that members log into collectively. + /// + public Guid SharedUserId { get; set; } + + /// + /// Gets or sets the identifiers of the members whose passwords unlock the shared account, + /// and whose own accounts receive its watched state. A usable group has at least two. + /// + [SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List.")] + [SuppressMessage("Design", "CA1002:Do not expose generic lists", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List.")] + public List MemberUserIds { get; set; } = new(); + + /// + /// Gets or sets a value indicating whether marking something unwatched on the shared account + /// also marks it unwatched for every member. When false, only the transition to watched + /// propagates. + /// + public bool SyncUnwatched { get; set; } = true; + + /// + /// Gets or sets a value indicating whether a member's play count is raised to at least one + /// when an item becomes watched. Play counts are never decremented. + /// + public bool SyncPlayCount { get; set; } + + /// + /// Gets or sets a value indicating whether this group is suspended. A group drops out of both + /// authentication and sync while disabled - set automatically if it falls below two members. + /// + public bool IsDisabled { get; set; } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Configuration/configPage.html b/Jellyfin.Plugin.WatchedTogether/Configuration/configPage.html new file mode 100644 index 0000000..84e9c29 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Configuration/configPage.html @@ -0,0 +1,262 @@ + + + + + Watched Together + + +
+
+
+ +
+

Watched Together

+

+ A shared account that several people log into with their own passwords. Anything + marked watched there is mirrored onto each member's own account. + This is not synchronized playback — for that, use Jellyfin's built-in SyncPlay. +

+
+ +
+

Existing groups

+
+
+ +
+

Create a group

+
+
+ + +
+ Leave blank to join the member names with the separator below. Names are + cosmetic — membership is tracked internally, not parsed from the name. +
+
+ +
+ + +
+ Any selected member's password will unlock the shared account. +
+
+ +
+ +
+ The shared account's library access is independent of each member's own + restrictions. If a member is normally blocked from a library but this + account is not, their password now reaches it. +
+
+ +
+ +
+
+
+ +
+

Settings

+
+
+ +
+ Typing an unrecognised name like alice+bob at the login + screen creates the shared account on the spot. Every name must belong to + an existing, enabled user, and the password must be one of theirs. + An existing account whose name contains the separator always wins. +
+
+ +
+ +
+ Turn this off to have auto-created accounts start with no library access + until you grant it. +
+
+ +
+ + +
+ Joins member names into an account name, and is the character split at + login above. '+' is valid on current Jellyfin; use '_' or '-' if your + server rejects it. +
+
+
+ +
+
+
+ +
+
+ + +
+ + diff --git a/Jellyfin.Plugin.WatchedTogether/Controllers/WatchedTogetherController.cs b/Jellyfin.Plugin.WatchedTogether/Controllers/WatchedTogetherController.cs new file mode 100644 index 0000000..04f7d85 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Controllers/WatchedTogetherController.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Mime; +using System.Threading.Tasks; +using Jellyfin.Plugin.WatchedTogether.Models; +using Jellyfin.Plugin.WatchedTogether.Services; +using MediaBrowser.Common.Api; +using MediaBrowser.Controller.Library; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Controllers; + +/// +/// Administrative endpoints backing the configuration page. +/// +[ApiController] +[Authorize(Policy = Policies.RequiresElevation)] +[Route("Plugins/WatchedTogether")] +[Produces(MediaTypeNames.Application.Json)] +public class WatchedTogetherController : ControllerBase +{ + private readonly IProvisioningService _provisioningService; + private readonly IUserManager _userManager; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The provisioning service. + /// The user manager. + /// The logger. + public WatchedTogetherController( + IProvisioningService provisioningService, + IUserManager userManager, + ILogger logger) + { + _provisioningService = provisioningService; + _userManager = userManager; + _logger = logger; + } + + /// + /// Gets every configured group, resolved against current user records. + /// + /// The configured groups. + [HttpGet("Groups")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult> GetGroups() + { + var config = Plugin.Instance?.Configuration; + if (config is null) + { + return Ok(Array.Empty()); + } + + var groups = config.Groups.Select(g => new GroupDto + { + SharedUserId = g.SharedUserId, + SharedUsername = _userManager.GetUserById(g.SharedUserId)?.Username ?? "(deleted)", + SyncUnwatched = g.SyncUnwatched, + SyncPlayCount = g.SyncPlayCount, + IsDisabled = g.IsDisabled, + Members = g.MemberUserIds.Select(id => new MemberDto + { + UserId = id, + Username = _userManager.GetUserById(id)?.Username ?? "(deleted)" + }).ToList() + }).ToList(); + + return Ok(groups); + } + + /// + /// Gets the users that may be selected as members - everyone who is not already a shared account. + /// + /// The eligible users. + [HttpGet("EligibleUsers")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult> GetEligibleUsers() + { + var sharedIds = Plugin.Instance?.Configuration.Groups + .Select(g => g.SharedUserId) + .ToHashSet() ?? []; + + var users = _userManager.Users + .Where(u => !sharedIds.Contains(u.Id)) + .Select(u => new MemberDto { UserId = u.Id, Username = u.Username }) + .OrderBy(u => u.Username, StringComparer.OrdinalIgnoreCase) + .ToList(); + + return Ok(users); + } + + /// + /// Creates a shared account and its group. + /// + /// The group to create. + /// The created group. + [HttpPost("Groups")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task> CreateGroup([FromBody] CreateGroupRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + try + { + var group = await _provisioningService.CreateGroupAsync( + request.MemberUserIds, + request.Name, + request.EnableAllFolders, + request.EnabledFolders).ConfigureAwait(false); + + return Ok(new GroupDto + { + SharedUserId = group.SharedUserId, + SharedUsername = _userManager.GetUserById(group.SharedUserId)?.Username ?? string.Empty, + SyncUnwatched = group.SyncUnwatched, + SyncPlayCount = group.SyncPlayCount, + IsDisabled = group.IsDisabled, + Members = group.MemberUserIds.Select(id => new MemberDto + { + UserId = id, + Username = _userManager.GetUserById(id)?.Username ?? "(deleted)" + }).ToList() + }); + } + catch (ArgumentException ex) + { + _logger.LogWarning(ex, "Rejected group creation request"); + return BadRequest(ex.Message); + } + } + + /// + /// Updates an existing group's membership and options. + /// + /// The shared account identifying the group. + /// The new membership and options. + /// No content on success. + [HttpPost("Groups/{sharedUserId}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task UpdateGroup( + [FromRoute] Guid sharedUserId, + [FromBody] UpdateGroupRequest request) + { + ArgumentNullException.ThrowIfNull(request); + + try + { + await _provisioningService.UpdateGroupAsync( + sharedUserId, + request.MemberUserIds, + request.SyncUnwatched, + request.SyncPlayCount, + request.IsDisabled).ConfigureAwait(false); + + return NoContent(); + } + catch (ArgumentException ex) + { + _logger.LogWarning(ex, "Rejected group update request"); + return BadRequest(ex.Message); + } + } + + /// + /// Deletes a group, optionally deleting its shared account too. + /// + /// The shared account identifying the group. + /// Whether to delete the shared account as well. + /// No content on success. + [HttpDelete("Groups/{sharedUserId}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task DeleteGroup( + [FromRoute] Guid sharedUserId, + [FromQuery] bool deleteSharedUser = false) + { + try + { + await _provisioningService.DeleteGroupAsync(sharedUserId, deleteSharedUser).ConfigureAwait(false); + return NoContent(); + } + catch (ArgumentException ex) + { + _logger.LogWarning(ex, "Rejected group deletion request"); + return BadRequest(ex.Message); + } + } +} diff --git a/Jellyfin.Plugin.Template/Jellyfin.Plugin.Template.csproj b/Jellyfin.Plugin.WatchedTogether/Jellyfin.Plugin.WatchedTogether.csproj similarity index 88% rename from Jellyfin.Plugin.Template/Jellyfin.Plugin.Template.csproj rename to Jellyfin.Plugin.WatchedTogether/Jellyfin.Plugin.WatchedTogether.csproj index fd1cdb1..825f125 100644 --- a/Jellyfin.Plugin.Template/Jellyfin.Plugin.Template.csproj +++ b/Jellyfin.Plugin.WatchedTogether/Jellyfin.Plugin.WatchedTogether.csproj @@ -2,7 +2,7 @@ net9.0 - Jellyfin.Plugin.Template + Jellyfin.Plugin.WatchedTogether true true enable @@ -11,10 +11,10 @@ - + runtime - + runtime diff --git a/Jellyfin.Plugin.WatchedTogether/Models/CreateGroupRequest.cs b/Jellyfin.Plugin.WatchedTogether/Models/CreateGroupRequest.cs new file mode 100644 index 0000000..8eea3ae --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Models/CreateGroupRequest.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.WatchedTogether.Models; + +/// +/// A request to create a shared account and its group. +/// +public class CreateGroupRequest +{ + /// + /// Gets or sets the members whose passwords will unlock the account. At least two. + /// + public IReadOnlyList MemberUserIds { get; set; } = Array.Empty(); + + /// + /// Gets or sets an explicit account name. When empty, one is generated from the member names. + /// + public string? Name { get; set; } + + /// + /// Gets or sets a value indicating whether the shared account may access all libraries. + /// + public bool EnableAllFolders { get; set; } = true; + + /// + /// Gets or sets the explicit libraries the shared account may access. + /// + public IReadOnlyList? EnabledFolders { get; set; } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Models/GroupDto.cs b/Jellyfin.Plugin.WatchedTogether/Models/GroupDto.cs new file mode 100644 index 0000000..4313486 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Models/GroupDto.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.WatchedTogether.Models; + +/// +/// A configured group, resolved for display. +/// +public class GroupDto +{ + /// + /// Gets or sets the shared account identifier. + /// + public Guid SharedUserId { get; set; } + + /// + /// Gets or sets the shared account's username. + /// + public string SharedUsername { get; set; } = string.Empty; + + /// + /// Gets or sets the group's members. + /// + public IReadOnlyList Members { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether unwatched state propagates too. + /// + public bool SyncUnwatched { get; set; } + + /// + /// Gets or sets a value indicating whether play counts are raised on watch. + /// + public bool SyncPlayCount { get; set; } + + /// + /// Gets or sets a value indicating whether the group is suspended. + /// + public bool IsDisabled { get; set; } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Models/MemberDto.cs b/Jellyfin.Plugin.WatchedTogether/Models/MemberDto.cs new file mode 100644 index 0000000..df0e453 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Models/MemberDto.cs @@ -0,0 +1,19 @@ +using System; + +namespace Jellyfin.Plugin.WatchedTogether.Models; + +/// +/// A member of a group, resolved to a current username. +/// +public class MemberDto +{ + /// + /// Gets or sets the member's user identifier. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets the member's username. + /// + public string Username { get; set; } = string.Empty; +} diff --git a/Jellyfin.Plugin.WatchedTogether/Models/UpdateGroupRequest.cs b/Jellyfin.Plugin.WatchedTogether/Models/UpdateGroupRequest.cs new file mode 100644 index 0000000..ca433dc --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Models/UpdateGroupRequest.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Plugin.WatchedTogether.Models; + +/// +/// A request to update an existing group. +/// +public class UpdateGroupRequest +{ + /// + /// Gets or sets the new member list. At least two. + /// + public IReadOnlyList MemberUserIds { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether unwatched state propagates too. + /// + public bool SyncUnwatched { get; set; } = true; + + /// + /// Gets or sets a value indicating whether play counts are raised on watch. + /// + public bool SyncPlayCount { get; set; } + + /// + /// Gets or sets a value indicating whether the group is suspended. + /// + public bool IsDisabled { get; set; } +} diff --git a/Jellyfin.Plugin.Template/Plugin.cs b/Jellyfin.Plugin.WatchedTogether/Plugin.cs similarity index 71% rename from Jellyfin.Plugin.Template/Plugin.cs rename to Jellyfin.Plugin.WatchedTogether/Plugin.cs index 445c2bc..f16fa8d 100644 --- a/Jellyfin.Plugin.Template/Plugin.cs +++ b/Jellyfin.Plugin.WatchedTogether/Plugin.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; using System.Globalization; -using Jellyfin.Plugin.Template.Configuration; +using Jellyfin.Plugin.WatchedTogether.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Plugins; using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Serialization; -namespace Jellyfin.Plugin.Template; +namespace Jellyfin.Plugin.WatchedTogether; /// -/// The main plugin. +/// The Watched Together plugin: shared viewing accounts whose watched state flows back to each +/// member's own account. /// public class Plugin : BasePlugin, IHasWebPages { @@ -26,10 +27,14 @@ public class Plugin : BasePlugin, IHasWebPages } /// - public override string Name => "Template"; + public override string Name => "Watched Together"; /// - public override Guid Id => Guid.Parse("eb5d7894-8eef-4b36-aa6f-5d124e828ce1"); + public override Guid Id => Guid.Parse("aa3288a0-e8c1-43e2-8045-8c3411142a5b"); + + /// + public override string Description => + "Lets several users share one viewing account, with watched state syncing back to each member."; /// /// Gets the current plugin instance. diff --git a/Jellyfin.Plugin.WatchedTogether/ServiceRegistrator.cs b/Jellyfin.Plugin.WatchedTogether/ServiceRegistrator.cs new file mode 100644 index 0000000..a472140 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/ServiceRegistrator.cs @@ -0,0 +1,28 @@ +using Jellyfin.Plugin.WatchedTogether.Auth; +using Jellyfin.Plugin.WatchedTogether.Services; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Authentication; +using MediaBrowser.Controller.Plugins; +using Microsoft.Extensions.DependencyInjection; + +namespace Jellyfin.Plugin.WatchedTogether; + +/// +/// Registers the plugin's services with the host. +/// +public class ServiceRegistrator : IPluginServiceRegistrator +{ + /// + public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost) + { + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); + + // Discovered by Jellyfin and matched to shared accounts via User.AuthenticationProviderId. + serviceCollection.AddSingleton(); + + serviceCollection.AddHostedService(); + serviceCollection.AddHostedService(); + } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/DynamicGroupService.cs b/Jellyfin.Plugin.WatchedTogether/Services/DynamicGroupService.cs new file mode 100644 index 0000000..b5f8df8 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/DynamicGroupService.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Jellyfin.Data; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Enums; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Cryptography; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Creates a shared account the first time someone logs in as "alice+bob". +/// +/// +/// +/// Jellyfin only routes a login to the providers with a null resolved user when no local +/// user matches the typed name. A real account named "alice+bob" therefore always wins, and this +/// code never sees it - the ambiguity between a group and a same-named user resolves in favour of +/// the real user automatically. +/// +/// +/// Every named member must exist and none may be a shared account, so an unrelated username +/// containing the separator simply fails to resolve and is rejected. +/// +/// +public class DynamicGroupService : IDynamicGroupService +{ + private readonly IUserManager _userManager; + private readonly IProvisioningService _provisioningService; + private readonly ICryptoProvider _cryptoProvider; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The user manager. + /// The provisioning service. + /// The crypto provider. + /// The logger. + public DynamicGroupService( + IUserManager userManager, + IProvisioningService provisioningService, + ICryptoProvider cryptoProvider, + ILogger logger) + { + _userManager = userManager; + _provisioningService = provisioningService; + _cryptoProvider = cryptoProvider; + _logger = logger; + } + + /// + public async Task TryCreateFromLoginAsync(string enteredUsername, string password) + { + var config = Plugin.Instance?.Configuration; + if (config is null || !config.EnableDynamicGroups) + { + return null; + } + + if (string.IsNullOrWhiteSpace(enteredUsername)) + { + return null; + } + + var separator = string.IsNullOrEmpty(config.NameSeparator) ? "+" : config.NameSeparator; + + var parts = enteredUsername + .Split(separator, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) + .ToList(); + + // Needs at least two names to be a group at all. + if (parts.Count < 2) + { + return null; + } + + // Every part must name a real, non-shared, enabled user. Anything else means this is not a + // group login, so fall through and let the attempt fail normally. + var members = new List(parts.Count); + foreach (var part in parts) + { + var member = _userManager.GetUserByName(part); + if (member is null) + { + _logger.LogDebug("Dynamic group login rejected: no user named {Part}", part); + return null; + } + + if (config.Groups.Any(g => g.SharedUserId == member.Id)) + { + _logger.LogWarning( + "Dynamic group login rejected: {Part} is itself a shared account", + part); + return null; + } + + if (member.HasPermission(PermissionKind.IsDisabled)) + { + _logger.LogWarning("Dynamic group login rejected: {Part} is disabled", part); + return null; + } + + if (members.Any(m => m.Id == member.Id)) + { + _logger.LogWarning("Dynamic group login rejected: {Part} named more than once", part); + return null; + } + + members.Add(member); + } + + // The password must belong to one of the named members. Without this any visitor could + // conjure a shared account out of two usernames they happened to know. + if (!members.Any(m => VerifyPassword(m, password))) + { + _logger.LogWarning( + "Dynamic group login for {Username} rejected: no named member's password matched", + enteredUsername); + return null; + } + + var group = await _provisioningService.CreateGroupAsync( + members.Select(m => m.Id).ToList(), + enteredUsername, + enableAllFolders: config.DynamicGroupsEnableAllFolders, + enabledFolders: null).ConfigureAwait(false); + + var sharedUser = _userManager.GetUserById(group.SharedUserId); + if (sharedUser is null) + { + return null; + } + + _logger.LogInformation( + "Created shared account {Username} on demand for {MemberCount} members", + sharedUser.Username, + members.Count); + + return new DynamicGroupResult(group, sharedUser.Username); + } + + /// + /// Verifies a submitted password against a member's live stored hash. + /// + /// The member to check. + /// The submitted password. + /// true if the password matches. + private bool VerifyPassword(User member, string password) + { + if (string.IsNullOrEmpty(member.Password)) + { + return false; + } + + try + { + return _cryptoProvider.Verify(PasswordHash.Parse(member.Password), password); + } + catch (Exception ex) when (ex is FormatException or ArgumentException) + { + // Never log the hash or the submitted password. + _logger.LogError(ex, "Could not parse the stored password hash for member {MemberId}", member.Id); + return false; + } + } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/GroupService.cs b/Jellyfin.Plugin.WatchedTogether/Services/GroupService.cs new file mode 100644 index 0000000..4baf1ec --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/GroupService.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Jellyfin.Data; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Enums; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Reads group membership from plugin configuration and resolves it against live user records. +/// +public class GroupService : IGroupService +{ + private readonly IUserManager _userManager; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The user manager. + /// The logger. + public GroupService(IUserManager userManager, ILogger logger) + { + _userManager = userManager; + _logger = logger; + } + + /// + public SharedGroup? GetGroupForSharedUser(Guid sharedUserId) + { + var config = Plugin.Instance?.Configuration; + if (config is null) + { + return null; + } + + var group = config.Groups.FirstOrDefault(g => g.SharedUserId == sharedUserId); + return group is null || group.IsDisabled ? null : group; + } + + /// + public IReadOnlyList GetEligibleMembers(SharedGroup group) + { + ArgumentNullException.ThrowIfNull(group); + + var members = new List(group.MemberUserIds.Count); + foreach (var memberId in group.MemberUserIds) + { + var member = _userManager.GetUserById(memberId); + if (member is null) + { + // Stale entry; PruneDeletedUser clears these when the deletion is observed. + continue; + } + + // A disabled member should no longer be able to unlock the shared account, and should + // not receive its watched state either. + if (member.HasPermission(PermissionKind.IsDisabled)) + { + continue; + } + + members.Add(member); + } + + return members; + } + + /// + public bool IsSharedAccount(Guid userId) + { + var config = Plugin.Instance?.Configuration; + return config is not null && config.Groups.Any(g => g.SharedUserId == userId); + } + + /// + public void PruneDeletedUser(Guid userId) + { + var plugin = Plugin.Instance; + if (plugin is null) + { + return; + } + + var config = plugin.Configuration; + var changed = false; + + // Drop groups whose shared account itself was deleted - there is nothing left to log into. + var orphaned = config.Groups.Where(g => g.SharedUserId == userId).ToList(); + foreach (var group in orphaned) + { + config.Groups.Remove(group); + changed = true; + _logger.LogInformation("Removed group for deleted shared account {SharedUserId}", userId); + } + + foreach (var group in config.Groups) + { + if (!group.MemberUserIds.Remove(userId)) + { + continue; + } + + changed = true; + _logger.LogInformation( + "Removed deleted member {MemberId} from group {SharedUserId}", + userId, + group.SharedUserId); + + // A group needs at least two members to mean anything; suspend rather than delete so + // an admin can add a replacement member and re-enable it. + if (group.MemberUserIds.Count < 2 && !group.IsDisabled) + { + group.IsDisabled = true; + _logger.LogWarning( + "Group {SharedUserId} disabled: fewer than two members remain", + group.SharedUserId); + } + } + + if (changed) + { + plugin.UpdateConfiguration(config); + } + } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/IDynamicGroupService.cs b/Jellyfin.Plugin.WatchedTogether/Services/IDynamicGroupService.cs new file mode 100644 index 0000000..7f97bef --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/IDynamicGroupService.cs @@ -0,0 +1,29 @@ +using System.Threading.Tasks; +using Jellyfin.Plugin.WatchedTogether.Configuration; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Creates shared accounts on demand from a separator-joined username typed at the login screen. +/// +public interface IDynamicGroupService +{ + /// + /// Attempts to authenticate a not-yet-existing shared account named like "alice+bob", creating + /// it if the submitted password belongs to one of the named members. + /// + /// The username typed at the login screen. + /// The submitted password. + /// + /// The created group and the shared account's username, or null if the name is not a + /// valid member combination or no named member's password matched. + /// + Task TryCreateFromLoginAsync(string enteredUsername, string password); +} + +/// +/// The outcome of a successful on-demand group creation. +/// +/// The group that was created. +/// The username of the shared account. +public record DynamicGroupResult(SharedGroup Group, string SharedUsername); diff --git a/Jellyfin.Plugin.WatchedTogether/Services/IGroupService.cs b/Jellyfin.Plugin.WatchedTogether/Services/IGroupService.cs new file mode 100644 index 0000000..83a54bd --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/IGroupService.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Plugin.WatchedTogether.Configuration; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Resolves shared-account groups from plugin configuration. +/// +public interface IGroupService +{ + /// + /// Gets the active group owning the given shared account, if any. + /// + /// The shared account identifier. + /// The group, or null if this user is not an enabled shared account. + SharedGroup? GetGroupForSharedUser(Guid sharedUserId); + + /// + /// Gets the members of a group that are currently eligible - existing and not disabled. + /// + /// The group whose members to resolve. + /// The eligible member users. + IReadOnlyList GetEligibleMembers(SharedGroup group); + + /// + /// Determines whether the given user is a shared account managed by this plugin, regardless + /// of whether its group is currently enabled. + /// + /// The user identifier to test. + /// true if the user is a managed shared account. + bool IsSharedAccount(Guid userId); + + /// + /// Removes a deleted user from every group, disabling any group left with fewer than two + /// members, and persists the result. + /// + /// The identifier of the user that was removed. + void PruneDeletedUser(Guid userId); +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/IProvisioningService.cs b/Jellyfin.Plugin.WatchedTogether/Services/IProvisioningService.cs new file mode 100644 index 0000000..76a4844 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/IProvisioningService.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Jellyfin.Plugin.WatchedTogether.Configuration; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Creates, updates and removes shared accounts and their groups. +/// +public interface IProvisioningService +{ + /// + /// Creates a shared account for the given members and records the group. + /// + /// The members whose passwords will unlock the account. At least two. + /// An explicit account name, or null to generate one from the member names. + /// Whether the shared account may access all libraries. + /// Explicit library identifiers, used when is false. + /// The created group. + Task CreateGroupAsync( + IReadOnlyList memberIds, + string? name, + bool enableAllFolders, + IReadOnlyList? enabledFolders); + + /// + /// Replaces the membership and options of an existing group. + /// + /// The shared account identifying the group. + /// The new member list. At least two. + /// Whether unwatched state propagates too. + /// Whether play counts are raised on watch. + /// Whether the group is suspended. + /// The updated group. + Task UpdateGroupAsync( + Guid sharedUserId, + IReadOnlyList memberIds, + bool syncUnwatched, + bool syncPlayCount, + bool isDisabled); + + /// + /// Removes a group, optionally deleting its shared account. + /// + /// The shared account identifying the group. + /// Whether to delete the shared Jellyfin account as well. + /// A task representing the removal. + Task DeleteGroupAsync(Guid sharedUserId, bool deleteSharedUser); +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/ProvisioningService.cs b/Jellyfin.Plugin.WatchedTogether/Services/ProvisioningService.cs new file mode 100644 index 0000000..5911b23 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/ProvisioningService.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Security.Cryptography; +using System.Threading.Tasks; +using Jellyfin.Data; +using Jellyfin.Database.Implementations.Enums; +using Jellyfin.Plugin.WatchedTogether.Configuration; +using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Creates and maintains shared accounts and the groups that describe them. +/// +public class ProvisioningService : IProvisioningService +{ + /// + /// The database column limit on usernames. A generated name is shortened to fit. + /// + private const int MaxUsernameLength = 255; + + /// + /// The provider key Jellyfin stores on a shared account to route its logins to us. Jellyfin + /// resolves providers by GetType().FullName, so this must match the provider type's + /// full name exactly. + /// + private static readonly string AuthProviderId = + typeof(Auth.SharedAccountAuthenticationProvider).FullName!; + + private readonly IUserManager _userManager; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The user manager. + /// The logger. + public ProvisioningService(IUserManager userManager, ILogger logger) + { + _userManager = userManager; + _logger = logger; + } + + /// + public async Task CreateGroupAsync( + IReadOnlyList memberIds, + string? name, + bool enableAllFolders, + IReadOnlyList? enabledFolders) + { + ArgumentNullException.ThrowIfNull(memberIds); + + var plugin = Plugin.Instance + ?? throw new InvalidOperationException("The plugin is not initialised."); + var config = plugin.Configuration; + + var distinctIds = memberIds.Distinct().ToList(); + if (distinctIds.Count < 2) + { + throw new ArgumentException("A group needs at least two distinct members.", nameof(memberIds)); + } + + var members = new List(distinctIds.Count); + foreach (var id in distinctIds) + { + var member = _userManager.GetUserById(id) + ?? throw new ArgumentException( + string.Format(CultureInfo.InvariantCulture, "No user exists with id {0}.", id), + nameof(memberIds)); + + // A shared account must not become a member of another group: its own login is already + // a union of other people's credentials, and nesting would compound that invisibly. + if (config.Groups.Any(g => g.SharedUserId == id)) + { + throw new ArgumentException( + string.Format( + CultureInfo.InvariantCulture, + "'{0}' is itself a shared account and cannot be a member of a group.", + member.Username), + nameof(memberIds)); + } + + members.Add(member); + } + + var accountName = string.IsNullOrWhiteSpace(name) + ? BuildDefaultName(members.Select(m => m.Username), config.NameSeparator) + : name.Trim(); + + var sharedUser = await _userManager.CreateUserAsync(accountName).ConfigureAwait(false); + + // Route this account's logins through our provider. Jellyfin matches providers by + // GetType().FullName, the same key the SSO plugin uses, and the assignment only sticks + // once the user is updated. + sharedUser.AuthenticationProviderId = AuthProviderId; + + // The shared account never authenticates against its own password - our provider checks + // member hashes instead. Setting a random one avoids leaving a passwordless account behind + // if the provider is ever unassigned. + await _userManager.ChangePassword(sharedUser, GenerateUnusedPassword()).ConfigureAwait(false); + await _userManager.UpdateUserAsync(sharedUser).ConfigureAwait(false); + + await ApplyLibraryAccessAsync(sharedUser.Id, enableAllFolders, enabledFolders).ConfigureAwait(false); + + var group = new SharedGroup + { + SharedUserId = sharedUser.Id, + MemberUserIds = distinctIds + }; + + config.Groups.Add(group); + plugin.UpdateConfiguration(config); + + _logger.LogInformation( + "Created shared account {Username} ({SharedUserId}) with {MemberCount} members", + sharedUser.Username, + sharedUser.Id, + distinctIds.Count); + + return group; + } + + /// + public Task UpdateGroupAsync( + Guid sharedUserId, + IReadOnlyList memberIds, + bool syncUnwatched, + bool syncPlayCount, + bool isDisabled) + { + ArgumentNullException.ThrowIfNull(memberIds); + + var plugin = Plugin.Instance + ?? throw new InvalidOperationException("The plugin is not initialised."); + var config = plugin.Configuration; + + var group = config.Groups.FirstOrDefault(g => g.SharedUserId == sharedUserId) + ?? throw new ArgumentException("No group exists for that shared account.", nameof(sharedUserId)); + + var distinctIds = memberIds.Distinct().ToList(); + if (distinctIds.Count < 2) + { + throw new ArgumentException("A group needs at least two distinct members.", nameof(memberIds)); + } + + foreach (var id in distinctIds) + { + if (_userManager.GetUserById(id) is null) + { + throw new ArgumentException( + string.Format(CultureInfo.InvariantCulture, "No user exists with id {0}.", id), + nameof(memberIds)); + } + + if (id == sharedUserId || config.Groups.Any(g => g.SharedUserId == id)) + { + throw new ArgumentException( + "A shared account cannot be a member of a group.", + nameof(memberIds)); + } + } + + group.MemberUserIds = distinctIds; + group.SyncUnwatched = syncUnwatched; + group.SyncPlayCount = syncPlayCount; + group.IsDisabled = isDisabled; + + plugin.UpdateConfiguration(config); + + _logger.LogInformation( + "Updated group {SharedUserId}: {MemberCount} members, disabled={IsDisabled}", + sharedUserId, + distinctIds.Count, + isDisabled); + + return Task.FromResult(group); + } + + /// + public async Task DeleteGroupAsync(Guid sharedUserId, bool deleteSharedUser) + { + var plugin = Plugin.Instance + ?? throw new InvalidOperationException("The plugin is not initialised."); + var config = plugin.Configuration; + + var group = config.Groups.FirstOrDefault(g => g.SharedUserId == sharedUserId) + ?? throw new ArgumentException("No group exists for that shared account.", nameof(sharedUserId)); + + // Drop the group first: if account deletion fails we are left with an orphaned account + // rather than a group pointing at a user that may be half-deleted. + config.Groups.Remove(group); + plugin.UpdateConfiguration(config); + + if (deleteSharedUser && _userManager.GetUserById(sharedUserId) is not null) + { + await _userManager.DeleteUserAsync(sharedUserId).ConfigureAwait(false); + _logger.LogInformation("Deleted shared account {SharedUserId}", sharedUserId); + } + + _logger.LogInformation("Removed group {SharedUserId}", sharedUserId); + } + + /// + /// Joins member names into a display name, falling back to a generic name if the result would + /// exceed the username column limit. Membership is tracked by GUID, so the name is cosmetic. + /// + /// The member usernames. + /// The configured separator. + /// A name that fits within the username length limit. + private static string BuildDefaultName(IEnumerable usernames, string separator) + { + var sep = string.IsNullOrEmpty(separator) ? "+" : separator; + var joined = string.Join(sep, usernames); + + if (joined.Length <= MaxUsernameLength) + { + return joined; + } + + // Truncating mid-name would produce something misleading, so switch to a neutral label + // with a short unique suffix instead. + return string.Format( + CultureInfo.InvariantCulture, + "Shared-{0}", + Guid.NewGuid().ToString("N")[..8]); + } + + /// + /// Generates a random password that is never used for authentication. + /// + /// A random password string. + private static string GenerateUnusedPassword() + => Convert.ToBase64String(RandomNumberGenerator.GetBytes(48)); + + /// + /// Sets library access on the shared account. + /// + /// The shared account. + /// Whether to grant access to every library. + /// The explicit library list when not granting all. + /// A task representing the update. + private async Task ApplyLibraryAccessAsync( + Guid sharedUserId, + bool enableAllFolders, + IReadOnlyList? enabledFolders) + { + var user = _userManager.GetUserById(sharedUserId); + if (user is null) + { + return; + } + + // Library access on the shared account is deliberate and independent of what each member + // can reach individually - any member's password opens whatever this account can see. + user.SetPermission(PermissionKind.EnableAllFolders, enableAllFolders); + await _userManager.UpdateUserAsync(user).ConfigureAwait(false); + + if (enableAllFolders) + { + return; + } + + var policy = _userManager.GetUserDto(user).Policy; + if (policy is null) + { + return; + } + + policy.EnableAllFolders = false; + policy.EnabledFolders = enabledFolders?.ToArray() ?? []; + await _userManager.UpdatePolicyAsync(sharedUserId, policy).ConfigureAwait(false); + } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/UserLifecycleService.cs b/Jellyfin.Plugin.WatchedTogether/Services/UserLifecycleService.cs new file mode 100644 index 0000000..a290c76 --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/UserLifecycleService.cs @@ -0,0 +1,86 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller.Library; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Keeps group membership consistent with the set of users that actually exist. +/// +/// +/// Jellyfin raises no user-deleted event that carries the removed id, so instead of subscribing to +/// deletions this reconciles configuration against live users at startup. Stale entries are also +/// skipped at read time by , so this is about keeping +/// stored configuration tidy and disabling groups that have fallen below two members. +/// +public sealed class UserLifecycleService : IHostedService +{ + private readonly IUserManager _userManager; + private readonly IGroupService _groupService; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The user manager. + /// The group service. + /// The logger. + public UserLifecycleService( + IUserManager userManager, + IGroupService groupService, + ILogger logger) + { + _userManager = userManager; + _groupService = groupService; + _logger = logger; + } + + /// + public Task StartAsync(CancellationToken cancellationToken) + { + try + { + Reconcile(); + } +#pragma warning disable CA1031 // Reconciliation must never prevent the server from starting. + catch (Exception ex) +#pragma warning restore CA1031 + { + _logger.LogError(ex, "Failed to reconcile Watched Together groups at startup"); + } + + return Task.CompletedTask; + } + + /// + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + /// + /// Removes references to users that no longer exist. + /// + private void Reconcile() + { + var config = Plugin.Instance?.Configuration; + if (config is null || config.Groups.Count == 0) + { + return; + } + + var liveIds = _userManager.UsersIds.ToHashSet(); + + var referenced = config.Groups + .SelectMany(g => g.MemberUserIds.Append(g.SharedUserId)) + .Distinct() + .ToList(); + + foreach (var id in referenced.Where(id => !liveIds.Contains(id))) + { + _logger.LogInformation("Pruning deleted user {UserId} from Watched Together groups", id); + _groupService.PruneDeletedUser(id); + } + } +} diff --git a/Jellyfin.Plugin.WatchedTogether/Services/WatchedStateSyncService.cs b/Jellyfin.Plugin.WatchedTogether/Services/WatchedStateSyncService.cs new file mode 100644 index 0000000..7e3108e --- /dev/null +++ b/Jellyfin.Plugin.WatchedTogether/Services/WatchedStateSyncService.cs @@ -0,0 +1,147 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Entities; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Plugin.WatchedTogether.Services; + +/// +/// Propagates played state from a shared account to each of its members, one way. +/// +public sealed class WatchedStateSyncService : IHostedService, IDisposable +{ + private readonly IUserDataManager _userDataManager; + private readonly IUserManager _userManager; + private readonly IGroupService _groupService; + private readonly ILogger _logger; + private bool _disposed; + + /// + /// Initializes a new instance of the class. + /// + /// The user data manager. + /// The user manager. + /// The group service. + /// The logger. + public WatchedStateSyncService( + IUserDataManager userDataManager, + IUserManager userManager, + IGroupService groupService, + ILogger logger) + { + _userDataManager = userDataManager; + _userManager = userManager; + _groupService = groupService; + _logger = logger; + } + + /// + public Task StartAsync(CancellationToken cancellationToken) + { + _userDataManager.UserDataSaved += OnUserDataSaved; + _logger.LogInformation("Watched Together sync started"); + return Task.CompletedTask; + } + + /// + public Task StopAsync(CancellationToken cancellationToken) + { + _userDataManager.UserDataSaved -= OnUserDataSaved; + _logger.LogInformation("Watched Together sync stopped"); + return Task.CompletedTask; + } + + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _userDataManager.UserDataSaved -= OnUserDataSaved; + _disposed = true; + } + + /// + /// Mirrors a shared account's played state onto its members. + /// + /// + /// No loop guard is needed. Writing to a member raises this event again with that member's id, + /// which is not a shared account id, so the handler returns immediately. The + /// Played equality check below suppresses redundant writes on top of that. + /// + private void OnUserDataSaved(object? sender, UserDataSaveEventArgs e) + { + if (e?.UserData is null || e.Item is null) + { + return; + } + + // UserDataSaved fires constantly during playback (progress ticks); only act on the reasons + // that actually represent a change in watched state. + if (e.SaveReason is not (UserDataSaveReason.PlaybackFinished + or UserDataSaveReason.TogglePlayed + or UserDataSaveReason.Import)) + { + return; + } + + var group = _groupService.GetGroupForSharedUser(e.UserId); + if (group is null) + { + return; + } + + var played = e.UserData.Played; + if (!played && !group.SyncUnwatched) + { + return; + } + + foreach (var member in _groupService.GetEligibleMembers(group)) + { + try + { + var data = _userDataManager.GetUserData(member, e.Item); + if (data is null || data.Played == played) + { + continue; + } + + data.Played = played; + + if (group.SyncPlayCount && played && data.PlayCount < 1) + { + data.PlayCount = 1; + } + + _userDataManager.SaveUserData( + member, + e.Item, + data, + UserDataSaveReason.TogglePlayed, + CancellationToken.None); + + _logger.LogDebug( + "Synced played={Played} for {ItemName} to member {MemberUsername}", + played, + e.Item.Name, + member.Username); + } +#pragma warning disable CA1031 // One member failing must not stop the rest from syncing. + catch (Exception ex) +#pragma warning restore CA1031 + { + _logger.LogError( + ex, + "Failed to sync played state for {ItemName} to member {MemberId}", + e.Item.Name, + member.Id); + } + } + } +} diff --git a/README.md b/README.md index cedfae9..cf75765 100644 --- a/README.md +++ b/README.md @@ -1,415 +1,289 @@ -# So you want to make a Jellyfin plugin +

Watched Together

-Awesome! This guide is for you. Jellyfin plugins are written using the dotnet standard framework. What that means is you can write them in any language that implements the CLI or the DLI and can compile to net8.0. The examples on this page are in C# because that is what most of Jellyfin is written in, but F#, Visual Basic, and IronPython should all be compatible once compiled. +

+A Jellyfin plugin that lets several people share one viewing account, +while everyone's watched list stays their own. +

-## 0. Things you need to get started +--- -- [Dotnet SDK 9.0](https://dotnet.microsoft.com/en-us/download/dotnet) +## The problem -- An editor of your choice. Some free choices are: +You have one television and one Jellyfin login on it. Two, three, four people use it. - [Visual Studio Code](https://code.visualstudio.com) +Whoever's account is signed in on that TV accumulates everything: *Continue Watching* fills with +someone else's half-finished documentaries, *Next Up* suggests episode 4 of a series you never +started, and the person whose account it is can no longer tell what they have actually seen. - [Visual Studio Community Edition](https://visualstudio.microsoft.com/downloads) +The usual workarounds are all bad: - [Mono Develop](https://www.monodevelop.com) +- **Everyone shares one account permanently.** Nobody's watched list means anything any more. +- **Everyone logs out and back in.** Nobody does this, especially not on a TV remote. +- **Everyone gets their own profile on the TV.** Same problem, switching is friction, so people stop. -## 0.5. Quickstarts +## What this plugin does -We have a number of quickstart options available to speed you along the way. +It creates a **shared account**, a real Jellyfin user that several people log into together; and gives it three special behaviours: -- [Download the Example Plugin Project](https://github.com/jellyfin/jellyfin-plugin-template/tree/master/Jellyfin.Plugin.Template) from this repository, open it in your IDE and go to [step 3](https://github.com/jellyfin/jellyfin-plugin-template#3-customize-plugin-information) +**1. The account creates itself when you log in.** +At the login screen, type `alice+bob` as the username and *your own* password. If no such account +exists yet, the plugin checks that `alice` and `bob` are both real users and that the password you +typed is one of theirs โ€” then creates the shared account and signs you straight into it. No +dashboard visit, no admin, no setup step. Next time, it is just there. -- Install our dotnet template by [downloading the dotnet-template/content folder from this repo](https://github.com/jellyfin/jellyfin-plugin-template/tree/master/dotnet-template/content) or off of Nuget (Coming soon) +**2. Any member's own password unlocks it.** +Alice types her password, Bob types his, and both get into the same shared account. Nobody has to +remember a new credential, and there is no shared password written on a sticky note. - ``` - dotnet new -i /path/to/templatefolder - ``` +**3. Whatever gets watched there is mirrored back to each member's own account.** +Finish an episode on the shared account and it is marked watched for Alice *and* Bob, on their +individual accounts. Their personal *Continue Watching* and *Next Up* stay correct, and when they +watch alone on their phone, the series picks up where the group left off. -- Run this command then skip to step 4 - - ``` - dotnet new Jellyfin-plugin -name MyPlugin - ``` - -If you'd rather start from scratch keep going on to step one. This assumes no specific editor or IDE and requires only the command line with dotnet in the path. - -## 1. Initialize Your Project - -Make a new dotnet standard project with the following command, it will make a directory for itself. +The sync is **one-way**: shared account โ†’ members. What Alice watches privately is her business and +never leaks into the shared account or onto Bob. ``` -dotnet new classlib -f net9.0 -n MyJellyfinPlugin + login as "alice+bob+carol" + with any one member's password + โ”‚ + โ–ผ (creates the account if it does not exist yet) + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + alice's password โ”‚ โ”‚ played โ”€โ”€โ–บ alice's account + bob's password โ”€โ”€โ–บโ”‚ shared account โ”‚ played โ”€โ”€โ–บ bob's account + carol's password โ”‚ "alice+bob+carol"โ”‚ played โ”€โ”€โ–บ carol's account + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + any one unlocks it watched state flows outward only ``` -Now add the Jellyfin shared libraries. +### This is not SyncPlay + +Jellyfin already has **SyncPlay**, which keeps playback *synchronized in time* across devices so +people in different places press play together. + +Watched Together solves a different problem: people watching *the same screen* who want their +*individual watched lists* to stay accurate. The two are complementary and can be used together. + +--- + +## How it works + +### Creating a group by logging in + +When you submit a username Jellyfin does not recognise, it offers the login to every enabled +authentication plugin before giving up. That is the hook this plugin uses. + +On an unrecognised name, it: + +1. Splits the name on the separator (`+` by default) โ€” `alice+bob+carol` โ†’ three parts. +2. Requires **every part** to be an existing, enabled user that is not itself a shared account. +3. Requires the submitted password to match **one of those members'** stored hashes. +4. Only then creates the shared account, and returns its name so Jellyfin completes the login. + +Step 3 is what stops this being an open door: knowing two usernames is not enough to bring an +account into being. If any check fails, the plugin declines and the login fails exactly as an +ordinary typo would. + +#### The name collision, and why it is harmless + +`+` is a legal Jellyfin username character: ``` -dotnet add package Jellyfin.Model -dotnet add package Jellyfin.Controller +^(?!\s)[\w \-'._@+]+(? - - runtime - - - runtime - - -``` -Note: Ensure the package reference version matches the install version of jellyfin server, otherwise the plugin will show as NotSupported. - -## 2. Set Up the Basics - -There are a few mandatory classes you'll need for a plugin so we need to make them. - -### PluginConfiguration - -Create a folder named "Configuration", and a PluginConfiguration.cs file inside. - -You can call it whatever you'd like really. This class is used to hold settings your plugin might need. We can leave it empty for now. This class should inherit from `MediaBrowser.Model.Plugins.BasePluginConfiguration` - -It should look something like the following: -```c# - using MediaBrowser.Model.Plugins; - - namespace MyJellyfinPlugin.Configuration; - class PluginConfiguration : BasePluginConfiguration - { - - } +https://gitea.tourolle.paris/dtourolle/WatchedTogether/raw/branch/master/manifest.json ``` -### Plugin +Then install **Watched Together** from the catalogue and restart Jellyfin. -This is the main class for your plugin and will reside in the root of your project. It will define your name, version and Id. It should inherit from `MediaBrowser.Common.Plugins.BasePlugin` +### Manual -It should look something like the following: -```c# - using MediaBrowser.Common.Plugins; - using MyJellyfinPlugin.Configuration; - - namespace MyJellyfinPlugin; - - class Plugin : BasePlugin - { - - } +Download the release `.zip`, extract it into a `WatchedTogether` folder inside your Jellyfin +`plugins` directory, and restart the server. + +--- + +## Setting up a group + +### The quick way: just log in + +On the shared device, at the Jellyfin login screen: + +- **Username:** `alice+bob` (the members' usernames, joined with `+`) +- **Password:** your own + +That is the whole setup. The account is created on first use and reused from then on. Add a third +person later by logging in once as `alice+bob+carol`. + +### The dashboard way + +If you would rather provision groups explicitly โ€” or you have turned auto-creation off: + +1. Go to **Dashboard โ†’ Plugins โ†’ Watched Together**. +2. Under **Create a group**, select **two or more** members. +3. Optionally give the account a name. Left blank, the member names are joined with `+`. +4. Decide whether the account should see all libraries (see the security note below). +5. Click **Create group**. + +Either way, a new user appears in your user list and can be renamed like any other. + +### Per-group options + +| Option | Default | Meaning | +| --- | --- | --- | +| Sync unwatched | on | Marking something *unwatched* on the shared account also marks it unwatched for every member. Turn this off to make sync additive: things only ever become watched. | +| Sync play count | off | Raise a member's play count to at least 1 when an item becomes watched. Play counts are never decreased. | +| Disabled | off | Suspends a group: it stops accepting logins and stops syncing, without deleting anything. | + +### Plugin settings + +| Setting | Default | Meaning | +| --- | --- | --- | +| Create groups automatically at login | on | Enables the `alice+bob` login flow described above. Turn off to require dashboard provisioning. | +| Auto-created accounts can access all libraries | on | Whether accounts made at the login screen start with full library access. Turn off to grant access deliberately. | +| Name separator | `+` | The character joining member names, and the one split at login. Use `_` or `-` if you prefer. | + +--- + +## Security notes + +Please read this before granting a shared account broad library access. + +- **Access is a union, and it is deliberate.** Any member's password opens the shared account, and + that account sees whatever libraries *you* granted *it*, independent of each member's own + restrictions. If a member is normally blocked from a library but the shared account is not, that + member's password now reaches it. Set the shared account's library access accordingly. +- **Auto-creation grants library access without an admin in the loop.** With both + *Create groups automatically at login* and *Auto-created accounts can access all libraries* on, + any user who knows a colleague's username can pair it with their own and reach a full-library + account. That is a real privilege escalation if your libraries are not uniformly visible. It is + still gated on a valid member password โ€” nobody gets in without one โ€” but if per-user library + restrictions matter to you, turn off *Auto-created accounts can access all libraries* (or + auto-creation entirely) and provision groups from the dashboard. +- **Disabled members are excluded.** A disabled Jellyfin user can no longer unlock the shared + account, and no longer receives watched state. +- **Shared accounts cannot be nested.** A shared account may not be a member of another group; this + is rejected at creation time. +- **Brute-force protection differs.** Because authentication bypasses Jellyfin's standard login + path (see above), the shared account does not inherit Jellyfin's built-in lockout counter. +- **Nothing sensitive is logged.** Submitted passwords and stored hashes are never written to logs. + +--- + +## Compatibility + +| | | +| --- | --- | +| Target ABI | Jellyfin **10.11.x** | +| Framework | .NET 9 | + +Verified against the 10.11.5 SDK: `IAuthenticationProvider` + `IRequiresResolvedUser`, +`ICryptoProvider.Verify`, `IUserDataManager.UserDataSaved`, and a 255-character username limit. + +Auto-creation depends on `UserManager.AuthenticateUser` offering unmatched usernames to every +enabled provider and re-querying the database afterwards ("the authentication provider might have +created it"). That behaviour is present in 10.11.5; if a future release changes it, auto-creation +stops working and dashboard provisioning continues to. + +Jellyfin's plugin API changes across minor versions, `IServerEntryPoint` gave way to +`IHostedService` around 10.9, and entity types moved namespaces in 10.11. Expect to rebuild against +the matching SDK when upgrading the server. + +--- + +## Building + +The plugin targets .NET 9. If your machine does not have that runtime, build in a container: + +```bash +docker run --rm -v "$PWD":/src -w /src mcr.microsoft.com/dotnet/sdk:9.0 \ + dotnet test Jellyfin.Plugin.WatchedTogether.sln -c Release ``` -Note: If you called your PluginConfiguration class something different, you need to put that between the <> +Or natively, with the .NET 9 SDK installed: -### Implement Required Properties - -The Plugin class needs a few properties implemented before it can work correctly. - -It needs an override on ID, an override on Name, and a constructor that follows a specific model. To get started you can use the following section. - -```c# -public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer){} -public override string Name => throw new System.NotImplementedException(); -public override Guid Id => Guid.Parse(""); +```bash +dotnet build Jellyfin.Plugin.WatchedTogether.sln -c Release +dotnet test Jellyfin.Plugin.WatchedTogether.sln -c Release ``` -## 3. Customize Plugin Information +To produce an installable plugin zip: -You need to populate some of your plugin's information. Go ahead a put in a string of the Name you've overridden name, and generate a GUID - -- **Windows Users**: you can use the Powershell command `New-Guid`, `[guid]::NewGuid()` or the Visual Studio GUID generator - -- **Linux and OS X Users**: you can use the Powershell Core command `New-Guid` or this command from your shell of choice: - - ```bash - od -x /dev/urandom | head -n1 | awk '{OFS="-"; srand($6); sub(/./,"4",$5); sub(/./,substr("89ab",1+rand()*4,1),$6); print $2$3,$4,$5,$6,$7$8$9}' - ``` - -or - - ```bash - uuidgen - ``` - -- Place that guid inside the `Guid.Parse("")` quotes to define your plugin's ID. - -## 4. Adding Functionality - -Congratulations, you now have everything you need for a perfectly functional functionless Jellyfin plugin! You can try it out right now if you'd like by compiling it, then placing the dll you generate in a subfolder (named after your plugin for example) within the plugins folder under your Jellyfin directory (Normally C:\Users\{YourUserName}\AppData\Local\jellyfin\plugins). If you want to try and hook it up to a debugger make sure you copy the generated PDB file alongside it. - -Most people aren't satisfied with just having an entry in a menu for their plugin, most people want to have some functionality, so lets look at how to add it. - -### 4a. Implement Interfaces - -If the functionality you are trying to add is functionality related to something that Jellyfin has an interface for you're in luck. Jellyfin uses some automatic discovery and injection to allow any interfaces you implement in your plugin to be available in Jellyfin. - -Here's some interfaces you could implement for common use cases: - -- **IAuthenticationProvider** - Allows you to add an authentication provider that can authenticate a user based on a name and a password, but that doesn't expect to deal with local users. -- **IBaseItemComparer** - Allows you to add sorting rules for dealing with media that will show up in sort menus -- **IIntroProvider** - Allows you to play a piece of media before another piece of media (i.e. a trailer before a movie, or a network bumper before an episode of a show) -- **IItemResolver** - Allows you to define custom media types -- **ILibraryPostScanTask** - Allows you to define a task that fires after scanning a library -- **IMetadataSaver** - Allows you to define a metadata standard that Jellyfin can use to write metadata -- **IResolverIgnoreRule** - Allows you to define subpaths that are ignored by media resolvers for use with another function (i.e. you wanted to have a theme song for each tv series stored in a subfolder that could be accessed by your plugin for playback in a menu). -- **IScheduledTask** - Allows you to create a scheduled task that will appear in the scheduled task lists on the dashboard. - -There are loads of other interfaces that can be used, but you'll need to poke around the API to get some info. If you're an expert on a particular interface, you should help [contribute some documentation](https://docs.jellyfin.org/general/contributing/index.html)! - -### 4b. Use plugin aimed interfaces to add custom functionality - -If your plugin doesn't fit perfectly neatly into a predefined interface, never fear, there are a set of interfaces and classes that allow your plugin to extend Jellyfin any which way you please. Here's a quick overview on how to use them - -- **IPluginConfigurationPage** - Allows you to have a plugin config page on the dashboard. If you used one of the quickstart example projects, a premade page with some useful components to work with has been created for you! If not you can check out this guide here for how to whip one up. - - **IPluginServiceRegistrator** - Will be located by Jellyfin at server startup and allows you to add services to the DI container to allow for injection in your plugin's classes later. - -- **IHostedService** - Allows you to run code as a background task that will be started at program startup and will remain in memory. See [Microsoft's documentation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&tabs=visual-studio#ihostedservice-interface) for more information. You can make as many of these as you need; make Jellyfin aware of them with an `IPluginServiceRegistrator`. It is wildly useful for loading configs or persisting state. **Be aware that your main plugin class (IBasePlugin) cannot also be a IHostedService.** - -- **ControllerBase** - Allows you to define custom REST-API endpoints. This is the default ASP.NET Web-API controller. You can use it exactly as you would in a normal Web-API project. Learn more about it [here](https://docs.microsoft.com/aspnet/core/web-api/?view=aspnetcore-5.0). - -Likewise you might need to get data and services from the Jellyfin core, Jellyfin provides a number of interfaces you can add as parameters to your plugin constructor which are then made available in your project (you can see the 2 mandatory ones that are needed by the plugin system in the constructor as is). - -- **IBlurayExaminer** - Allows you to examine blu-ray folders -- **IDtoService** - Allows you to create data transport objects, presumably to send to other plugins or to the core -- **ILibraryManager** - Allows you to directly access the media libraries without hopping through the API -- **ILocalizationManager** - Allows you tap into the main localization engine which governs translations, rating systems, units etc... -- **INetworkManager** - Allows you to get information about the server's networking status -- **IServerApplicationPaths** - Allows you to get the running server's paths -- **IServerConfigurationManager** - Allows you to write or read server configuration data into the application paths -- **ITaskManager** - Allows you to execute and manipulate scheduled tasks -- **IUserManager** - Allows you to retrieve user info and user library related info -- **IXmlSerializer** - Allows you to use the main xml serializer -- **IZipClient** - Allows you to use the core zip client for compressing and decompressing data - -## 5. Create a Repository - -- [See blog post](https://jellyfin.org/posts/plugin-updates/) - -## 6. Set Up Debugging - -Debugging can be set up by creating tasks which will be executed when running the plugin project. The specifics on setting up these tasks are not included as they may differ from IDE to IDE. The following list describes the general process: - -- Compile the plugin in debug mode. -- Create the plugin directory if it doesn't exist. -- Copy the plugin into your server's plugin directory. The server will then execute it. -- Make sure to set the working directory of the program being debugged to the working directory of the Jellyfin Server. -- Start the server. - -Some IDEs like Visual Studio Code may need the following compile flags to compile the plugin: - -```shell -dotnet build Your-Plugin.sln /property:GenerateFullPaths=true /consoleloggerparameters:NoSummary +```bash +jprm plugin build . ``` -These flags generate the full paths for file names and **do not** generate a summary during the build process as this may lead to duplicate errors in the problem panel of your IDE. +### CI -### 6.a Set Up Debugging on Visual Studio +Gitea Actions workflows live in [.gitea/workflows/](.gitea/workflows/): -Visual Studio allows developers to connect to other processes and debug them, setting breakpoints and inspecting the variables of the program. We can set this up following this steps: -On this section we will explain how to set up our solution to enable debugging before the server starts. +| Workflow | Trigger | Does | +| --- | --- | --- | +| `test.yaml` | push / PR | Debug build and test run, uploads `.trx` results | +| `build.yaml` | push / PR to `master` | Release build, tests, and a date-versioned plugin zip | +| `release.yaml` | tag `v*.*.*` | Builds, creates a Gitea release, and updates `manifest.json` | -1. Right-click on the solution, And click on Add -> Existing Project... -2. Locate Jellyfin executable in your installation folder and click on 'Open'. It is called `Jellyfin.exe`. Now The solution will have a new "Project" called Jellyfin. This is the executable, not the source code of Jellyfin. -3. Right-click on this new project and click on 'Set up as Startup Project' -4. Right-click on this new project and click on 'Properties' -5. Make sure that the 'Attach' parameter is set to 'No' +All three run in the builder image defined by [Dockerfile.builder](Dockerfile.builder): -From now on, everytime you click on start from Visual Studio, it will start Jellyfin attached to the debugger! +```bash +docker build -f Dockerfile.builder -t gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest . +docker push gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest +``` -The only thing left to do is to compile the project as it is specified a few lines above and you are done. +--- -### 6.b Automate the Setup on Visual Studio Code +## License -Visual Studio Code allows developers to automate the process of starting all necessary dependencies to start debugging the plugin. This guide assumes the reader is familiar with the [documentation on debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) and has read the documentation in this file. It is assumed that the Jellyfin Server has already been compiled once. However, should one desire to automatically compile the server before the start of the debugging session, this can be easily implemented, but is not further discussed here. - -A full example, which aims to be portable may be found in this repo's `.vscode` folder. - -This example expects you to clone `jellyfin`, `jellyfin-web` and `jellyfin-plugin-template` under the same parent directory, though you can customize this in `settings.json` - -1. Create a `settings.json` file inside your `.vscode` folder, to specify common options specific to your local setup. - ```jsonc - { - // jellyfinDir : The directory of the cloned jellyfin server project - // This needs to be built once before it can be used - "jellyfinDir" : "${workspaceFolder}/../jellyfin/Jellyfin.Server", - // jellyfinWebDir : The directory of the cloned jellyfin-web project - // This needs to be built once before it can be used - "jellyfinWebDir" : "${workspaceFolder}/../jellyfin-web", - // jellyfinDataDir : the root data directory for a running jellyfin instance - // This is where jellyfin stores its configs, plugins, metadata etc - // This is platform specific by default, but on Windows defaults to - // ${env:LOCALAPPDATA}/jellyfin - "jellyfinDataDir" : "${env:LOCALAPPDATA}/jellyfin", - // The name of the plugin - "pluginName" : "Jellyfin.Plugin.Template", - } - ``` - -1. To automate the launch process, create a new `launch.json` file for C# projects inside the `.vscode` folder. The example below shows only the relevant parts of the file. Adjustments to your specific setup and operating system may be required. - - ```jsonc - { - // Paths and plugin names are configured in settings.json - "version": "0.2.0", - "configurations": [ - { - "type": "coreclr", - "name": "Launch", - "request": "launch", - "preLaunchTask": "build-and-copy", - "program": "${config:jellyfinDir}/bin/Debug/net8.0/jellyfin.dll", - "args": [ - //"--nowebclient" - "--webdir", - "${config:jellyfinWebDir}/dist/" - ], - "cwd": "${config:jellyfinDir}", - } - ] - } - - ``` - - The `request` type is specified as `launch`, as this `launch.json` file will start the Jellyfin Server process. The `preLaunchTask` defines a task that will run before the Jellyfin Server starts. More on this later. It is important to set the `program` path to the Jellyin Server program and set the current working directory (`cwd`) to the working directory of the Jellyfin Server. - The `args` option allows to specify arguments to be passed to the server, e.g. whether Jellyfin should start with the web-client or without it. - -2. Create a `tasks.json` file inside your `.vscode` folder and specify a `build-and-copy` task that will run in `sequence` order. This tasks depends on multiple other tasks and all of those other tasks can be defined as simple `shell` tasks that run commands like the `cp` command to copy a file. The sequence to run those tasks in is given below. Please note that it might be necessary to adjust the examples for your specific setup and operating system. - - The full file is shown here - Specific sections will be discussed in depth - ```jsonc - { - // Paths and plugin name are configured in settings.json - "version": "2.0.0", - "tasks": [ - { - // A chain task - build the plugin, then copy it to your - // jellyfin server's plugin directory - "label": "build-and-copy", - "dependsOrder": "sequence", - "dependsOn": ["build", "make-plugin-dir", "copy-dll"] - }, - { - // Build the plugin - "label": "build", - "command": "dotnet", - "type": "shell", - "args": [ - "publish", - "${workspaceFolder}/${config:pluginName}.sln", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "group": "build", - "presentation": { - "reveal": "silent" - }, - "problemMatcher": "$msCompile" - }, - { - // Ensure the plugin directory exists before trying to use it - "label": "make-plugin-dir", - "type": "shell", - "command": "mkdir", - "args": [ - "-Force", - "-Path", - "${config:jellyfinDataDir}/plugins/${config:pluginName}/" - ] - }, - { - // Copy the plugin dll to the jellyfin plugin install path - // This command copies every .dll from the build directory to the plugin dir - // Usually, you probablly only need ${config:pluginName}.dll - // But some plugins may bundle extra requirements - "label": "copy-dll", - "type": "shell", - "command": "cp", - "args": [ - "./${config:pluginName}/bin/Debug/net8.0/publish/*", - "${config:jellyfinDataDir}/plugins/${config:pluginName}/" - ] - - }, - ] - } - - ``` - 1. The "build-and-copy" task which triggers all of the other tasks - ```jsonc - { - // A chain task - build the plugin, then copy it to your - // jellyfin server's plugin directory - "label": "build-and-copy", - "dependsOrder": "sequence", - "dependsOn": ["build", "make-plugin-dir", "copy-dll"] - }, - ``` - 2. A build task. This task builds the plugin without generating summary, but with full paths for file names enabled. - - ```jsonc - { - // Build the plugin - "label": "build", - "command": "dotnet", - "type": "shell", - "args": [ - "publish", - "${workspaceFolder}/${config:pluginName}.sln", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "group": "build", - "presentation": { - "reveal": "silent" - }, - "problemMatcher": "$msCompile" - }, - ``` - - 3. A tasks which creates the necessary plugin directory and a sub-folder for the specific plugin. The plugin directory is located below the [data directory](https://jellyfin.org/docs/general/administration/configuration.html) of the Jellyfin Server. As an example, the following path can be used for the bookshelf plugin: `$HOME/.local/share/jellyfin/plugins/Bookshelf/` - ```jsonc - { - // Ensure the plugin directory exists before trying to use it - "label": "make-plugin-dir", - "type": "shell", - "command": "mkdir", - "args": [ - "-Force", - "-Path", - "${config:jellyfinDataDir}/plugins/${config:pluginName}/" - ] - }, - ``` - - 4. A tasks which copies the plugin dll which has been built in step 2.1. The file is copied into it's specific plugin directory within the server's plugin directory. - - ```jsonc - { - // Copy the plugin dll to the jellyfin plugin install path - // This command copies every .dll from the build directory to the plugin dir - // Usually, you probablly only need ${config:pluginName}.dll - // But some plugins may bundle extra requirements - "label": "copy-dll", - "type": "shell", - "command": "cp", - "args": [ - "./${config:pluginName}/bin/Debug/net8.0/publish/*", - "${config:jellyfinDataDir}/plugins/${config:pluginName}/" - ] - }, - ``` - -## Licensing - -Licensing is a complex topic. This repository features a GPLv3 license template that can be used to provide a good default license for your plugin. You may alter this if you like, but if you do a permissive license must be chosen. - -Due to how plugins in Jellyfin work, when your plugin is compiled into a binary, it will link against the various Jellyfin binary NuGet packages. These packages are licensed under the GPLv3. Thus, due to the nature and restrictions of the GPL, the binary plugin you get will also be licensed under the GPLv3. - -If you accept the default GPLv3 license from this template, all will be good. However if you choose a different license, please keep this fact in mind, as it might not always be obvious that an, e.g. MIT-licensed plugin would become GPLv3 when compiled. - -Please note that this also means making "proprietary", source-unavailable, or otherwise "hidden" plugins for public consumption is not permitted. To build a Jellyfin plugin for distribution to others, it must be under the GPLv3 or a permissive open-source license that can be linked against the GPLv3. +GPL-3.0. See [LICENSE](LICENSE). diff --git a/build.yaml b/build.yaml index 168daa7..fe7ebdc 100644 --- a/build.yaml +++ b/build.yaml @@ -1,16 +1,27 @@ --- -name: "Template" -guid: "eb5d7894-8eef-4b36-aa6f-5d124e828ce1" +name: "Watched Together" +guid: "aa3288a0-e8c1-43e2-8045-8c3411142a5b" version: "1.0.0.0" -targetAbi: "10.9.0.0" -framework: "net8.0" -overview: "Short description about your plugin" +targetAbi: "10.11.0.0" +framework: "net9.0" +overview: "One shared login for several people; watched state flows back to each member's own account" description: > - This is a longer description that can span more than one - line and include details about your plugin. + Watched Together lets several users share a single viewing account. Any member's + password unlocks the shared account, and anything marked watched or unwatched there + propagates one-way to each member's individual account. + + This is not synchronized playback - for watching in lockstep across devices, use + Jellyfin's built-in SyncPlay. Watched Together solves the "one TV, one login, but + everyone's Continue Watching should stay correct" problem instead. category: "General" -owner: "jellyfin" +owner: "dtourolle" artifacts: -- "Jellyfin.Plugin.Template.dll" +- "Jellyfin.Plugin.WatchedTogether.dll" +build_type: "dotnet" +dotnet_configuration: "Release" +dotnet_framework: "net9.0" +# Point at the plugin project rather than the solution so the test project is not packaged. +project: "Jellyfin.Plugin.WatchedTogether/Jellyfin.Plugin.WatchedTogether.csproj" changelog: > - changelog + Initial release: provisioned shared accounts, multi-password authentication, + and one-way played-state sync to members. diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..96fb756 --- /dev/null +++ b/manifest.json @@ -0,0 +1,11 @@ +[ + { + "guid": "aa3288a0-e8c1-43e2-8045-8c3411142a5b", + "name": "Watched Together", + "description": "Lets several users share a single viewing account. Any member's password unlocks the shared account, and anything marked watched or unwatched there propagates one-way to each member's individual account. This is not synchronized playback - for that, use Jellyfin's built-in SyncPlay.", + "overview": "One shared login for several people; watched state flows back to each member's own account", + "owner": "dtourolle", + "category": "General", + "versions": [] + } +]