Implement Watched Together shared viewing accounts
🏗️ Build Plugin / build (push) Has been cancelled
🧪 Test Plugin / test (push) Has been cancelled

Replaces the plugin template with a working plugin that lets several
users share one viewing account while keeping their individual watched
lists accurate.

Three pieces:

- Auto-creating groups. Logging in as "alice+bob" with any named
  member's own password provisions the shared account and signs you in.
  Verified against 10.11.5: AuthenticateUser offers unmatched usernames
  to every enabled provider and re-queries afterwards, which is the hook
  this relies on. Gated on a real member password so knowing two
  usernames is not enough to create an account.

- Multi-password authentication. IRequiresResolvedUser hands us the
  resolved shared account; each member's live stored hash is checked via
  ICryptoProvider.Verify. Deliberately avoids re-entering
  UserManager.AuthenticateUser, which would trip every member's
  failed-attempt counter whenever a different member's password matched.

- One-way played-state sync. Shared account to members only, filtered to
  PlaybackFinished/TogglePlayed/Import so playback progress ticks are
  ignored. No loop guard needed: member writes carry a non-shared id.

Membership is stored as user IDs rather than re-parsed from the username,
so shared accounts can be renamed freely. The +/name collision resolves
itself because Jellyfin only consults the plugin when no local user
matches the typed name.

Targets Jellyfin 10.11.x / net9.0. Adds Gitea CI (test, build, release),
a builder image, and 34 tests covering the auth and sync rules.
This commit is contained in:
2026-07-29 00:00:13 +02:00
parent 7a9dbdafcc
commit 7be07d16a2
46 changed files with 3319 additions and 690 deletions
+89
View File
@@ -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 }}
+166
View File
@@ -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 <<EOF
{
"version": "${VERSION}",
"changelog": "Release ${VERSION}",
"targetAbi": "10.11.0.0",
"sourceUrl": "${DOWNLOAD_URL}",
"checksum": "${CHECKSUM}",
"timestamp": "${TIMESTAMP}"
}
EOF
)
jq --argjson newver "${NEW_VERSION}" '.[0].versions = [$newver] + .[0].versions' manifest.json > 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 }}
+59
View File
@@ -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 }}
-18
View File
@@ -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
-20
View File
@@ -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 }}
-13
View File
@@ -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: .
-16
View File
@@ -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 }}
-18
View File
@@ -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 }}
-20
View File
@@ -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
-12
View File
@@ -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 }}
-18
View File
@@ -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
+1
View File
@@ -3,3 +3,4 @@ obj/
.vs/ .vs/
.idea/ .idea/
artifacts artifacts
spec.md
+18
View File
@@ -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
-28
View File
@@ -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
@@ -1,57 +0,0 @@
using MediaBrowser.Model.Plugins;
namespace Jellyfin.Plugin.Template.Configuration;
/// <summary>
/// The configuration options.
/// </summary>
public enum SomeOptions
{
/// <summary>
/// Option one.
/// </summary>
OneOption,
/// <summary>
/// Second option.
/// </summary>
AnotherOption
}
/// <summary>
/// Plugin configuration.
/// </summary>
public class PluginConfiguration : BasePluginConfiguration
{
/// <summary>
/// Initializes a new instance of the <see cref="PluginConfiguration"/> class.
/// </summary>
public PluginConfiguration()
{
// set default options here
Options = SomeOptions.AnotherOption;
TrueFalseSetting = true;
AnInteger = 2;
AString = "string";
}
/// <summary>
/// Gets or sets a value indicating whether some true or false setting is enabled..
/// </summary>
public bool TrueFalseSetting { get; set; }
/// <summary>
/// Gets or sets an integer setting.
/// </summary>
public int AnInteger { get; set; }
/// <summary>
/// Gets or sets a string setting.
/// </summary>
public string AString { get; set; }
/// <summary>
/// Gets or sets an enum option.
/// </summary>
public SomeOptions Options { get; set; }
}
@@ -1,79 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Template</title>
</head>
<body>
<div id="TemplateConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
<div data-role="content">
<div class="content-primary">
<form id="TemplateConfigForm">
<div class="selectContainer">
<label class="selectLabel" for="Options">Several Options</label>
<select is="emby-select" id="Options" name="Options" class="emby-select-withcolor emby-select">
<option id="optOneOption" value="OneOption">One Option</option>
<option id="optAnotherOption" value="AnotherOption">Another Option</option>
</select>
</div>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="AnInteger">An Integer</label>
<input id="AnInteger" name="AnInteger" type="number" is="emby-input" min="0" />
<div class="fieldDescription">A Description</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="TrueFalseSetting" name="TrueFalseCheckBox" type="checkbox" is="emby-checkbox" />
<span>A Checkbox</span>
</label>
</div>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="AString">A String</label>
<input id="AString" name="AString" type="text" is="emby-input" />
<div class="fieldDescription">Another Description</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Save</span>
</button>
</div>
</form>
</div>
</div>
<script type="text/javascript">
var TemplateConfig = {
pluginUniqueId: 'eb5d7894-8eef-4b36-aa6f-5d124e828ce1'
};
document.querySelector('#TemplateConfigPage')
.addEventListener('pageshow', function() {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(TemplateConfig.pluginUniqueId).then(function (config) {
document.querySelector('#Options').value = config.Options;
document.querySelector('#AnInteger').value = config.AnInteger;
document.querySelector('#TrueFalseSetting').checked = config.TrueFalseSetting;
document.querySelector('#AString').value = config.AString;
Dashboard.hideLoadingMsg();
});
});
document.querySelector('#TemplateConfigForm')
.addEventListener('submit', function(e) {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(TemplateConfig.pluginUniqueId).then(function (config) {
config.Options = document.querySelector('#Options').value;
config.AnInteger = document.querySelector('#AnInteger').value;
config.TrueFalseSetting = document.querySelector('#TrueFalseSetting').checked;
config.AString = document.querySelector('#AString').value;
ApiClient.updatePluginConfiguration(TemplateConfig.pluginUniqueId, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result);
});
});
e.preventDefault();
return false;
});
</script>
</div>
</body>
</html>
@@ -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;
/// <summary>
/// Covers the rule that makes this plugin work: any member's password unlocks the shared account,
/// and nothing else does.
/// </summary>
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;
}
/// <summary>
/// Builds a provider whose crypto accepts exactly the (hash, password) pairs given.
/// </summary>
private static SharedAccountAuthenticationProvider MakeProvider(
SharedGroup? group,
IReadOnlyList<User> members,
params (string Hash, string Password)[] validPairs)
=> MakeProvider(group, members, null, validPairs);
/// <summary>
/// Builds a provider, optionally with a dynamic-group service that returns
/// <paramref name="dynamicResult"/> for an unresolved username.
/// </summary>
private static SharedAccountAuthenticationProvider MakeProvider(
SharedGroup? group,
IReadOnlyList<User> members,
DynamicGroupResult? dynamicResult,
params (string Hash, string Password)[] validPairs)
{
// ICryptoProvider.Verify takes a ReadOnlySpan<char>, 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<IGroupService>();
groups.Setup(g => g.GetGroupForSharedUser(It.IsAny<Guid>())).Returns(group);
groups.Setup(g => g.GetEligibleMembers(It.IsAny<SharedGroup>())).Returns(members);
var dynamic = new Mock<IDynamicGroupService>();
dynamic.Setup(d => d.TryCreateFromLoginAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(dynamicResult);
return new SharedAccountAuthenticationProvider(
crypto,
groups.Object,
dynamic.Object,
NullLogger<SharedAccountAuthenticationProvider>.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<AuthenticationException>(
() => 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<AuthenticationException>(
() => 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<AuthenticationException>(
() => 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<AuthenticationException>(
() => 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<AuthenticationException>(
() => 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<NotSupportedException>(
() => provider.ChangePassword(MakeUser("alice+bob", null), "new-pw"));
}
}
@@ -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;
/// <summary>
/// Covers creating a shared account on the fly from a name typed at the login screen.
/// </summary>
/// <remarks>
/// These tests drive <see cref="DynamicGroupService"/> through a stubbed user manager. They rely on
/// <see cref="Plugin.Instance"/> configuration, which is set up per test via
/// <see cref="PluginTestContext"/>.
/// </remarks>
[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<IProvisioningService> Provisioning);
private static Harness MakeService(
IReadOnlyList<User> knownUsers,
params (string Hash, string Password)[] validPairs)
{
var userManager = new Mock<IUserManager>();
userManager.Setup(m => m.GetUserByName(It.IsAny<string>()))
.Returns((string n) =>
{
foreach (var u in knownUsers)
{
if (string.Equals(u.Username, n, StringComparison.OrdinalIgnoreCase))
{
return u;
}
}
return null!;
});
var provisioning = new Mock<IProvisioningService>();
var createdShared = MakeUser("created-shared");
provisioning.Setup(p => p.CreateGroupAsync(
It.IsAny<IReadOnlyList<Guid>>(),
It.IsAny<string?>(),
It.IsAny<bool>(),
It.IsAny<IReadOnlyList<Guid>?>()))
.ReturnsAsync((IReadOnlyList<Guid> ids, string? name, bool _, IReadOnlyList<Guid>? _) =>
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<DynamicGroupService>.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<IReadOnlyList<Guid>>(ids => ids.Count == 2),
"alice+bob",
It.IsAny<bool>(),
It.IsAny<IReadOnlyList<Guid>?>()),
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<IReadOnlyList<Guid>>(ids => ids.Count == 3),
It.IsAny<string?>(),
It.IsAny<bool>(),
It.IsAny<IReadOnlyList<Guid>?>()),
Times.Once);
}
}
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<!-- Test code is exempt from the strict analyzer profile the plugin itself uses. -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<AnalysisMode>Default</AnalysisMode>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CA1707;SA0001;CS1591</NoWarn>
<!--
The plugin targets net9.0 to match Jellyfin 10.11's ABI, but a machine may only have a newer
runtime installed. Rolling the test host forward to the latest major lets the suite run
without pinning developers to a .NET 9 runtime.
-->
<RollForward>LatestMajor</RollForward>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Jellyfin.Plugin.WatchedTogether/Jellyfin.Plugin.WatchedTogether.csproj" />
</ItemGroup>
<ItemGroup>
<!--
The plugin excludes the runtime assets of these packages because the Jellyfin server supplies
them at load time. Tests run without a server, so they need the real assemblies copied to the
output directory.
-->
<PackageReference Include="Jellyfin.Controller" Version="10.11.5" />
<PackageReference Include="Jellyfin.Model" Version="10.11.5" />
</ItemGroup>
</Project>
@@ -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;
/// <summary>
/// Marks tests that read or write the process-wide <see cref="Plugin.Instance"/>, so xUnit runs
/// them serially rather than letting parallel classes clobber each other's configuration.
/// </summary>
[CollectionDefinition(nameof(PluginTestContext))]
public class PluginTestCollection : ICollectionFixture<object>
{
}
/// <summary>
/// Constructs a real <see cref="Plugin"/> backed by a temporary directory so that services reading
/// <see cref="Plugin.Instance"/> have configuration to work with, and cleans up afterwards.
/// </summary>
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<T> derives its data folder from PluginsPath and its config file from
// PluginConfigurationsPath, so both must resolve to a real directory.
var paths = new Mock<IApplicationPaths>();
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<IXmlSerializer>();
serializer.Setup(s => s.DeserializeFromFile(It.IsAny<Type>(), It.IsAny<string>()))
.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.
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Cryptography;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// A crypto provider that accepts exactly the (stored hash, submitted password) pairs it is given.
/// </summary>
/// <remarks>
/// Hand-written rather than mocked: <see cref="ICryptoProvider.Verify"/> takes a
/// <c>ReadOnlySpan&lt;char&gt;</c>, and a ref struct cannot be used as a generic type argument to
/// Moq's <c>It.IsAny&lt;T&gt;</c>.
/// </remarks>
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<char> 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<char> password)
=> throw new NotSupportedException();
public byte[] GenerateSalt() => throw new NotSupportedException();
public byte[] GenerateSalt(int length) => throw new NotSupportedException();
}
@@ -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;
/// <summary>
/// Covers propagation of played state from a shared account to its members.
/// </summary>
public class WatchedStateSyncTests
{
private static readonly Guid SharedId = Guid.NewGuid();
private sealed class Harness
{
public Mock<IUserDataManager> UserData { get; } = new();
public Mock<IGroupService> 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<User> members,
bool memberAlreadyPlayed = false,
int memberPlayCount = 0)
{
var h = new Harness();
h.Groups.Setup(g => g.GetGroupForSharedUser(It.IsAny<Guid>())).Returns(group);
h.Groups.Setup(g => g.GetEligibleMembers(It.IsAny<SharedGroup>())).Returns(members);
h.UserData.Setup(m => m.GetUserData(It.IsAny<User>(), It.IsAny<BaseItem>()))
.Returns(() => new UserItemData
{
Key = "k",
Played = memberAlreadyPlayed,
PlayCount = memberPlayCount
});
h.UserData.Setup(m => m.SaveUserData(
It.IsAny<User>(),
It.IsAny<BaseItem>(),
It.IsAny<UserItemData>(),
It.IsAny<UserDataSaveReason>(),
It.IsAny<CancellationToken>()))
.Callback<User, BaseItem, UserItemData, UserDataSaveReason, CancellationToken>(
(u, _, d, _, _) => h.Saves.Add((u, d.Played, d.PlayCount)));
h.Service = new WatchedStateSyncService(
h.UserData.Object,
new Mock<IUserManager>().Object,
h.Groups.Object,
NullLogger<WatchedStateSyncService>.Instance);
return h;
}
/// <summary>
/// Raises UserDataSaved as the server would, by starting the service so it subscribes.
/// </summary>
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);
}
}
+42
View File
@@ -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
@@ -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;
/// <summary>
/// Authenticates a shared account against the passwords of each of its members.
/// </summary>
/// <remarks>
/// <para>
/// Jellyfin selects a provider per user via <c>User.AuthenticationProviderId</c>, so this provider
/// only ever sees shared accounts that provisioning assigned to it. Implementing
/// <see cref="IRequiresResolvedUser"/> means Jellyfin hands us the already-resolved shared account
/// rather than us having to look it up by name.
/// </para>
/// <para>
/// Verification reads each member's stored hash directly instead of calling
/// <c>IUserManager.AuthenticateUser</c>. Going through the normal flow would trip every member's
/// failed-attempt counter each time a <em>different</em> 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.
/// </para>
/// </remarks>
public class SharedAccountAuthenticationProvider : IAuthenticationProvider, IRequiresResolvedUser
{
private readonly ICryptoProvider _cryptoProvider;
private readonly Services.IGroupService _groupService;
private readonly Services.IDynamicGroupService _dynamicGroupService;
private readonly ILogger<SharedAccountAuthenticationProvider> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="SharedAccountAuthenticationProvider"/> class.
/// </summary>
/// <param name="cryptoProvider">The crypto provider used to verify stored password hashes.</param>
/// <param name="groupService">The group service.</param>
/// <param name="dynamicGroupService">The on-demand group creation service.</param>
/// <param name="logger">The logger.</param>
public SharedAccountAuthenticationProvider(
ICryptoProvider cryptoProvider,
Services.IGroupService groupService,
Services.IDynamicGroupService dynamicGroupService,
ILogger<SharedAccountAuthenticationProvider> logger)
{
_cryptoProvider = cryptoProvider;
_groupService = groupService;
_dynamicGroupService = dynamicGroupService;
_logger = logger;
}
/// <inheritdoc />
public string Name => "Watched Together Shared Account";
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
/// <remarks>
/// Jellyfin calls the <see cref="IRequiresResolvedUser"/> overload instead, so this exists only
/// to satisfy the interface.
/// </remarks>
public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
=> Authenticate(username, password, null);
/// <inheritdoc />
public async Task<ProviderAuthenticationResult> 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.");
}
/// <inheritdoc />
/// <remarks>
/// A shared account always has a password in the sense that matters to Jellyfin: some member
/// credential is required. Returning <c>false</c> would let clients offer a passwordless login.
/// </remarks>
public bool HasPassword(User user) => true;
/// <inheritdoc />
/// <remarks>
/// 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.
/// </remarks>
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.");
}
/// <summary>
/// Verifies a submitted password against a member's live stored hash.
/// </summary>
/// <param name="member">The member whose stored credential to check.</param>
/// <param name="password">The submitted password.</param>
/// <returns><c>true</c> if the password matches.</returns>
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;
}
}
}
@@ -0,0 +1,47 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using MediaBrowser.Model.Plugins;
namespace Jellyfin.Plugin.WatchedTogether.Configuration;
/// <summary>
/// Plugin configuration. Holds the authoritative record of which members belong to which
/// shared account.
/// </summary>
public class PluginConfiguration : BasePluginConfiguration
{
/// <summary>
/// Gets or sets the configured shared-account groups.
/// </summary>
[SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List<T>.")]
[SuppressMessage("Design", "CA1002:Do not expose generic lists", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List<T>.")]
public List<SharedGroup> Groups { get; set; } = new();
/// <summary>
/// Gets or sets the separator used to join member names into a shared account name. Also the
/// separator split at login when <see cref="EnableDynamicGroups"/> is on.
/// </summary>
public string NameSeparator { get; set; } = "+";
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// The account is only created if every named part is an existing, enabled, non-shared user
/// <em>and</em> 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.
/// </remarks>
public bool EnableDynamicGroups { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether accounts created on demand may access all libraries.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public bool DynamicGroupsEnableAllFolders { get; set; } = true;
}
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Jellyfin.Plugin.WatchedTogether.Configuration;
/// <summary>
/// The association between one shared account and the members who may unlock it.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public class SharedGroup
{
/// <summary>
/// Gets or sets the identifier of the shared account that members log into collectively.
/// </summary>
public Guid SharedUserId { get; set; }
/// <summary>
/// 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.
/// </summary>
[SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List<T>.")]
[SuppressMessage("Design", "CA1002:Do not expose generic lists", Justification = "Plugin configuration is round-tripped by the XML serializer, which requires a settable List<T>.")]
public List<Guid> MemberUserIds { get; set; } = new();
/// <summary>
/// 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.
/// </summary>
public bool SyncUnwatched { get; set; } = true;
/// <summary>
/// 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.
/// </summary>
public bool SyncPlayCount { get; set; }
/// <summary>
/// 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.
/// </summary>
public bool IsDisabled { get; set; }
}
@@ -0,0 +1,262 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Watched Together</title>
</head>
<body>
<div id="WatchedTogetherConfigPage" data-role="page" class="page type-interior pluginConfigurationPage"
data-require="emby-input,emby-button,emby-select,emby-checkbox">
<div data-role="content">
<div class="content-primary">
<div class="verticalSection">
<h2 class="sectionTitle">Watched Together</h2>
<p class="fieldDescription">
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 &mdash; for that, use Jellyfin's built-in SyncPlay.
</p>
</div>
<div class="verticalSection">
<h3 class="sectionTitle">Existing groups</h3>
<div id="groupsList"></div>
</div>
<div class="verticalSection">
<h3 class="sectionTitle">Create a group</h3>
<form id="CreateGroupForm">
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="NewGroupName">Account name</label>
<input id="NewGroupName" name="NewGroupName" type="text" is="emby-input" />
<div class="fieldDescription">
Leave blank to join the member names with the separator below. Names are
cosmetic &mdash; membership is tracked internally, not parsed from the name.
</div>
</div>
<div class="selectContainer">
<label class="selectLabel" for="MemberSelect">Members (select at least two)</label>
<select is="emby-select" id="MemberSelect" multiple size="8"
class="emby-select-withcolor emby-select"></select>
<div class="fieldDescription">
Any selected member's password will unlock the shared account.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="EnableAllFolders" type="checkbox" is="emby-checkbox" checked />
<span>Grant access to all libraries</span>
</label>
<div class="fieldDescription">
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.
</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Create group</span>
</button>
</div>
</form>
</div>
<div class="verticalSection">
<h3 class="sectionTitle">Settings</h3>
<form id="SettingsForm">
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="EnableDynamicGroups" type="checkbox" is="emby-checkbox" />
<span>Create groups automatically at login</span>
</label>
<div class="fieldDescription">
Typing an unrecognised name like <code>alice+bob</code> 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.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="DynamicGroupsEnableAllFolders" type="checkbox" is="emby-checkbox" />
<span>Auto-created accounts can access all libraries</span>
</label>
<div class="fieldDescription">
Turn this off to have auto-created accounts start with no library access
until you grant it.
</div>
</div>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="NameSeparator">Name separator</label>
<input id="NameSeparator" name="NameSeparator" type="text" is="emby-input" maxlength="3" />
<div class="fieldDescription">
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.
</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Save</span>
</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
(function () {
var pluginUniqueId = 'aa3288a0-e8c1-43e2-8045-8c3411142a5b';
var page;
function apiUrl(path) {
return ApiClient.getUrl('Plugins/WatchedTogether/' + path);
}
function loadEligibleUsers() {
return ApiClient.getJSON(apiUrl('EligibleUsers')).then(function (users) {
var select = page.querySelector('#MemberSelect');
select.innerHTML = users.map(function (u) {
return '<option value="' + u.UserId + '">' + u.Username + '</option>';
}).join('');
});
}
function renderGroups(groups) {
var container = page.querySelector('#groupsList');
if (!groups.length) {
container.innerHTML = '<p class="fieldDescription">No groups configured yet.</p>';
return;
}
container.innerHTML = groups.map(function (g) {
var members = g.Members.map(function (m) { return m.Username; }).join(', ');
var status = g.IsDisabled ? ' <span style="opacity:.7">(disabled)</span>' : '';
return '<div class="listItem" style="padding:.6em 0;border-bottom:1px solid rgba(255,255,255,.1)">' +
'<h3 style="margin:0">' + g.SharedUsername + status + '</h3>' +
'<div class="fieldDescription">Members: ' + members + '</div>' +
'<div class="fieldDescription">' +
'Sync unwatched: ' + (g.SyncUnwatched ? 'yes' : 'no') +
' &middot; Sync play count: ' + (g.SyncPlayCount ? 'yes' : 'no') + '</div>' +
'<button is="emby-button" type="button" class="raised btnDeleteGroup" ' +
'data-id="' + g.SharedUserId + '" data-name="' + g.SharedUsername + '">' +
'<span>Delete</span></button>' +
'</div>';
}).join('');
container.querySelectorAll('.btnDeleteGroup').forEach(function (btn) {
btn.addEventListener('click', function () {
var id = btn.getAttribute('data-id');
var name = btn.getAttribute('data-name');
// Deleting the account too is destructive, so make it an explicit choice.
Dashboard.confirm(
'Also delete the shared account "' + name + '"? Choose Cancel to keep the account and only remove the group.',
'Delete group',
function (deleteUser) {
var url = apiUrl('Groups/' + id + '?deleteSharedUser=' + (deleteUser ? 'true' : 'false'));
ApiClient.ajax({ type: 'DELETE', url: url }).then(function () {
Dashboard.alert('Group deleted.');
loadGroups();
loadEligibleUsers();
});
});
});
});
}
function loadGroups() {
return ApiClient.getJSON(apiUrl('Groups')).then(renderGroups);
}
document.querySelector('#WatchedTogetherConfigPage').addEventListener('pageshow', function () {
page = this;
Dashboard.showLoadingMsg();
Promise.all([
loadGroups(),
loadEligibleUsers(),
ApiClient.getPluginConfiguration(pluginUniqueId).then(function (config) {
page.querySelector('#NameSeparator').value = config.NameSeparator || '+';
page.querySelector('#EnableDynamicGroups').checked = config.EnableDynamicGroups;
page.querySelector('#DynamicGroupsEnableAllFolders').checked = config.DynamicGroupsEnableAllFolders;
})
]).then(function () {
Dashboard.hideLoadingMsg();
}, function () {
Dashboard.hideLoadingMsg();
});
});
document.querySelector('#CreateGroupForm').addEventListener('submit', function (e) {
e.preventDefault();
var selected = Array.prototype.slice
.call(page.querySelector('#MemberSelect').selectedOptions)
.map(function (o) { return o.value; });
if (selected.length < 2) {
Dashboard.alert('Select at least two members.');
return false;
}
Dashboard.showLoadingMsg();
ApiClient.ajax({
type: 'POST',
url: apiUrl('Groups'),
contentType: 'application/json',
data: JSON.stringify({
MemberUserIds: selected,
Name: page.querySelector('#NewGroupName').value || null,
EnableAllFolders: page.querySelector('#EnableAllFolders').checked,
EnabledFolders: null
})
}).then(function () {
Dashboard.hideLoadingMsg();
Dashboard.alert('Group created.');
page.querySelector('#NewGroupName').value = '';
loadGroups();
loadEligibleUsers();
}, function (response) {
Dashboard.hideLoadingMsg();
if (response && response.text) {
response.text().then(function (msg) {
Dashboard.alert({ title: 'Could not create group', message: msg });
});
} else {
Dashboard.alert('Could not create group.');
}
});
return false;
});
document.querySelector('#SettingsForm').addEventListener('submit', function (e) {
e.preventDefault();
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(pluginUniqueId).then(function (config) {
config.NameSeparator = page.querySelector('#NameSeparator').value || '+';
config.EnableDynamicGroups = page.querySelector('#EnableDynamicGroups').checked;
config.DynamicGroupsEnableAllFolders = page.querySelector('#DynamicGroupsEnableAllFolders').checked;
ApiClient.updatePluginConfiguration(pluginUniqueId, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result);
});
});
return false;
});
})();
</script>
</div>
</body>
</html>
@@ -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;
/// <summary>
/// Administrative endpoints backing the configuration page.
/// </summary>
[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<WatchedTogetherController> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="WatchedTogetherController"/> class.
/// </summary>
/// <param name="provisioningService">The provisioning service.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="logger">The logger.</param>
public WatchedTogetherController(
IProvisioningService provisioningService,
IUserManager userManager,
ILogger<WatchedTogetherController> logger)
{
_provisioningService = provisioningService;
_userManager = userManager;
_logger = logger;
}
/// <summary>
/// Gets every configured group, resolved against current user records.
/// </summary>
/// <returns>The configured groups.</returns>
[HttpGet("Groups")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<IEnumerable<GroupDto>> GetGroups()
{
var config = Plugin.Instance?.Configuration;
if (config is null)
{
return Ok(Array.Empty<GroupDto>());
}
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);
}
/// <summary>
/// Gets the users that may be selected as members - everyone who is not already a shared account.
/// </summary>
/// <returns>The eligible users.</returns>
[HttpGet("EligibleUsers")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<IEnumerable<MemberDto>> 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);
}
/// <summary>
/// Creates a shared account and its group.
/// </summary>
/// <param name="request">The group to create.</param>
/// <returns>The created group.</returns>
[HttpPost("Groups")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<GroupDto>> 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);
}
}
/// <summary>
/// Updates an existing group's membership and options.
/// </summary>
/// <param name="sharedUserId">The shared account identifying the group.</param>
/// <param name="request">The new membership and options.</param>
/// <returns>No content on success.</returns>
[HttpPost("Groups/{sharedUserId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> 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);
}
}
/// <summary>
/// Deletes a group, optionally deleting its shared account too.
/// </summary>
/// <param name="sharedUserId">The shared account identifying the group.</param>
/// <param name="deleteSharedUser">Whether to delete the shared account as well.</param>
/// <returns>No content on success.</returns>
[HttpDelete("Groups/{sharedUserId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult> 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);
}
}
}
@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net9.0</TargetFramework>
<RootNamespace>Jellyfin.Plugin.Template</RootNamespace> <RootNamespace>Jellyfin.Plugin.WatchedTogether</RootNamespace>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
@@ -11,10 +11,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="10.9.11" > <PackageReference Include="Jellyfin.Controller" Version="10.11.5">
<ExcludeAssets>runtime</ExcludeAssets> <ExcludeAssets>runtime</ExcludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Jellyfin.Model" Version="10.9.11"> <PackageReference Include="Jellyfin.Model" Version="10.11.5">
<ExcludeAssets>runtime</ExcludeAssets> <ExcludeAssets>runtime</ExcludeAssets>
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.WatchedTogether.Models;
/// <summary>
/// A request to create a shared account and its group.
/// </summary>
public class CreateGroupRequest
{
/// <summary>
/// Gets or sets the members whose passwords will unlock the account. At least two.
/// </summary>
public IReadOnlyList<Guid> MemberUserIds { get; set; } = Array.Empty<Guid>();
/// <summary>
/// Gets or sets an explicit account name. When empty, one is generated from the member names.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the shared account may access all libraries.
/// </summary>
public bool EnableAllFolders { get; set; } = true;
/// <summary>
/// Gets or sets the explicit libraries the shared account may access.
/// </summary>
public IReadOnlyList<Guid>? EnabledFolders { get; set; }
}
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.WatchedTogether.Models;
/// <summary>
/// A configured group, resolved for display.
/// </summary>
public class GroupDto
{
/// <summary>
/// Gets or sets the shared account identifier.
/// </summary>
public Guid SharedUserId { get; set; }
/// <summary>
/// Gets or sets the shared account's username.
/// </summary>
public string SharedUsername { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the group's members.
/// </summary>
public IReadOnlyList<MemberDto> Members { get; set; } = Array.Empty<MemberDto>();
/// <summary>
/// Gets or sets a value indicating whether unwatched state propagates too.
/// </summary>
public bool SyncUnwatched { get; set; }
/// <summary>
/// Gets or sets a value indicating whether play counts are raised on watch.
/// </summary>
public bool SyncPlayCount { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the group is suspended.
/// </summary>
public bool IsDisabled { get; set; }
}
@@ -0,0 +1,19 @@
using System;
namespace Jellyfin.Plugin.WatchedTogether.Models;
/// <summary>
/// A member of a group, resolved to a current username.
/// </summary>
public class MemberDto
{
/// <summary>
/// Gets or sets the member's user identifier.
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// Gets or sets the member's username.
/// </summary>
public string Username { get; set; } = string.Empty;
}
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
namespace Jellyfin.Plugin.WatchedTogether.Models;
/// <summary>
/// A request to update an existing group.
/// </summary>
public class UpdateGroupRequest
{
/// <summary>
/// Gets or sets the new member list. At least two.
/// </summary>
public IReadOnlyList<Guid> MemberUserIds { get; set; } = Array.Empty<Guid>();
/// <summary>
/// Gets or sets a value indicating whether unwatched state propagates too.
/// </summary>
public bool SyncUnwatched { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether play counts are raised on watch.
/// </summary>
public bool SyncPlayCount { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the group is suspended.
/// </summary>
public bool IsDisabled { get; set; }
}
@@ -1,16 +1,17 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using Jellyfin.Plugin.Template.Configuration; using Jellyfin.Plugin.WatchedTogether.Configuration;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Serialization;
namespace Jellyfin.Plugin.Template; namespace Jellyfin.Plugin.WatchedTogether;
/// <summary> /// <summary>
/// The main plugin. /// The Watched Together plugin: shared viewing accounts whose watched state flows back to each
/// member's own account.
/// </summary> /// </summary>
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{ {
@@ -26,10 +27,14 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
} }
/// <inheritdoc /> /// <inheritdoc />
public override string Name => "Template"; public override string Name => "Watched Together";
/// <inheritdoc /> /// <inheritdoc />
public override Guid Id => Guid.Parse("eb5d7894-8eef-4b36-aa6f-5d124e828ce1"); public override Guid Id => Guid.Parse("aa3288a0-e8c1-43e2-8045-8c3411142a5b");
/// <inheritdoc />
public override string Description =>
"Lets several users share one viewing account, with watched state syncing back to each member.";
/// <summary> /// <summary>
/// Gets the current plugin instance. /// Gets the current plugin instance.
@@ -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;
/// <summary>
/// Registers the plugin's services with the host.
/// </summary>
public class ServiceRegistrator : IPluginServiceRegistrator
{
/// <inheritdoc />
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
{
serviceCollection.AddSingleton<IGroupService, GroupService>();
serviceCollection.AddSingleton<IProvisioningService, ProvisioningService>();
serviceCollection.AddSingleton<IDynamicGroupService, DynamicGroupService>();
// Discovered by Jellyfin and matched to shared accounts via User.AuthenticationProviderId.
serviceCollection.AddSingleton<IAuthenticationProvider, SharedAccountAuthenticationProvider>();
serviceCollection.AddHostedService<WatchedStateSyncService>();
serviceCollection.AddHostedService<UserLifecycleService>();
}
}
@@ -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;
/// <summary>
/// Creates a shared account the first time someone logs in as "alice+bob".
/// </summary>
/// <remarks>
/// <para>
/// Jellyfin only routes a login to the providers with a null resolved user when <em>no</em> 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
public class DynamicGroupService : IDynamicGroupService
{
private readonly IUserManager _userManager;
private readonly IProvisioningService _provisioningService;
private readonly ICryptoProvider _cryptoProvider;
private readonly ILogger<DynamicGroupService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="DynamicGroupService"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="provisioningService">The provisioning service.</param>
/// <param name="cryptoProvider">The crypto provider.</param>
/// <param name="logger">The logger.</param>
public DynamicGroupService(
IUserManager userManager,
IProvisioningService provisioningService,
ICryptoProvider cryptoProvider,
ILogger<DynamicGroupService> logger)
{
_userManager = userManager;
_provisioningService = provisioningService;
_cryptoProvider = cryptoProvider;
_logger = logger;
}
/// <inheritdoc />
public async Task<DynamicGroupResult?> 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<User>(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);
}
/// <summary>
/// Verifies a submitted password against a member's live stored hash.
/// </summary>
/// <param name="member">The member to check.</param>
/// <param name="password">The submitted password.</param>
/// <returns><c>true</c> if the password matches.</returns>
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;
}
}
}
@@ -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;
/// <summary>
/// Reads group membership from plugin configuration and resolves it against live user records.
/// </summary>
public class GroupService : IGroupService
{
private readonly IUserManager _userManager;
private readonly ILogger<GroupService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="GroupService"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="logger">The logger.</param>
public GroupService(IUserManager userManager, ILogger<GroupService> logger)
{
_userManager = userManager;
_logger = logger;
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
public IReadOnlyList<User> GetEligibleMembers(SharedGroup group)
{
ArgumentNullException.ThrowIfNull(group);
var members = new List<User>(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;
}
/// <inheritdoc />
public bool IsSharedAccount(Guid userId)
{
var config = Plugin.Instance?.Configuration;
return config is not null && config.Groups.Any(g => g.SharedUserId == userId);
}
/// <inheritdoc />
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);
}
}
}
@@ -0,0 +1,29 @@
using System.Threading.Tasks;
using Jellyfin.Plugin.WatchedTogether.Configuration;
namespace Jellyfin.Plugin.WatchedTogether.Services;
/// <summary>
/// Creates shared accounts on demand from a separator-joined username typed at the login screen.
/// </summary>
public interface IDynamicGroupService
{
/// <summary>
/// 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.
/// </summary>
/// <param name="enteredUsername">The username typed at the login screen.</param>
/// <param name="password">The submitted password.</param>
/// <returns>
/// The created group and the shared account's username, or <c>null</c> if the name is not a
/// valid member combination or no named member's password matched.
/// </returns>
Task<DynamicGroupResult?> TryCreateFromLoginAsync(string enteredUsername, string password);
}
/// <summary>
/// The outcome of a successful on-demand group creation.
/// </summary>
/// <param name="Group">The group that was created.</param>
/// <param name="SharedUsername">The username of the shared account.</param>
public record DynamicGroupResult(SharedGroup Group, string SharedUsername);
@@ -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;
/// <summary>
/// Resolves shared-account groups from plugin configuration.
/// </summary>
public interface IGroupService
{
/// <summary>
/// Gets the active group owning the given shared account, if any.
/// </summary>
/// <param name="sharedUserId">The shared account identifier.</param>
/// <returns>The group, or <c>null</c> if this user is not an enabled shared account.</returns>
SharedGroup? GetGroupForSharedUser(Guid sharedUserId);
/// <summary>
/// Gets the members of a group that are currently eligible - existing and not disabled.
/// </summary>
/// <param name="group">The group whose members to resolve.</param>
/// <returns>The eligible member users.</returns>
IReadOnlyList<User> GetEligibleMembers(SharedGroup group);
/// <summary>
/// Determines whether the given user is a shared account managed by this plugin, regardless
/// of whether its group is currently enabled.
/// </summary>
/// <param name="userId">The user identifier to test.</param>
/// <returns><c>true</c> if the user is a managed shared account.</returns>
bool IsSharedAccount(Guid userId);
/// <summary>
/// Removes a deleted user from every group, disabling any group left with fewer than two
/// members, and persists the result.
/// </summary>
/// <param name="userId">The identifier of the user that was removed.</param>
void PruneDeletedUser(Guid userId);
}
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Jellyfin.Plugin.WatchedTogether.Configuration;
namespace Jellyfin.Plugin.WatchedTogether.Services;
/// <summary>
/// Creates, updates and removes shared accounts and their groups.
/// </summary>
public interface IProvisioningService
{
/// <summary>
/// Creates a shared account for the given members and records the group.
/// </summary>
/// <param name="memberIds">The members whose passwords will unlock the account. At least two.</param>
/// <param name="name">An explicit account name, or <c>null</c> to generate one from the member names.</param>
/// <param name="enableAllFolders">Whether the shared account may access all libraries.</param>
/// <param name="enabledFolders">Explicit library identifiers, used when <paramref name="enableAllFolders"/> is false.</param>
/// <returns>The created group.</returns>
Task<SharedGroup> CreateGroupAsync(
IReadOnlyList<Guid> memberIds,
string? name,
bool enableAllFolders,
IReadOnlyList<Guid>? enabledFolders);
/// <summary>
/// Replaces the membership and options of an existing group.
/// </summary>
/// <param name="sharedUserId">The shared account identifying the group.</param>
/// <param name="memberIds">The new member list. At least two.</param>
/// <param name="syncUnwatched">Whether unwatched state propagates too.</param>
/// <param name="syncPlayCount">Whether play counts are raised on watch.</param>
/// <param name="isDisabled">Whether the group is suspended.</param>
/// <returns>The updated group.</returns>
Task<SharedGroup> UpdateGroupAsync(
Guid sharedUserId,
IReadOnlyList<Guid> memberIds,
bool syncUnwatched,
bool syncPlayCount,
bool isDisabled);
/// <summary>
/// Removes a group, optionally deleting its shared account.
/// </summary>
/// <param name="sharedUserId">The shared account identifying the group.</param>
/// <param name="deleteSharedUser">Whether to delete the shared Jellyfin account as well.</param>
/// <returns>A task representing the removal.</returns>
Task DeleteGroupAsync(Guid sharedUserId, bool deleteSharedUser);
}
@@ -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;
/// <summary>
/// Creates and maintains shared accounts and the groups that describe them.
/// </summary>
public class ProvisioningService : IProvisioningService
{
/// <summary>
/// The database column limit on usernames. A generated name is shortened to fit.
/// </summary>
private const int MaxUsernameLength = 255;
/// <summary>
/// The provider key Jellyfin stores on a shared account to route its logins to us. Jellyfin
/// resolves providers by <c>GetType().FullName</c>, so this must match the provider type's
/// full name exactly.
/// </summary>
private static readonly string AuthProviderId =
typeof(Auth.SharedAccountAuthenticationProvider).FullName!;
private readonly IUserManager _userManager;
private readonly ILogger<ProvisioningService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ProvisioningService"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="logger">The logger.</param>
public ProvisioningService(IUserManager userManager, ILogger<ProvisioningService> logger)
{
_userManager = userManager;
_logger = logger;
}
/// <inheritdoc />
public async Task<SharedGroup> CreateGroupAsync(
IReadOnlyList<Guid> memberIds,
string? name,
bool enableAllFolders,
IReadOnlyList<Guid>? 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<Jellyfin.Database.Implementations.Entities.User>(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;
}
/// <inheritdoc />
public Task<SharedGroup> UpdateGroupAsync(
Guid sharedUserId,
IReadOnlyList<Guid> 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);
}
/// <inheritdoc />
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);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="usernames">The member usernames.</param>
/// <param name="separator">The configured separator.</param>
/// <returns>A name that fits within the username length limit.</returns>
private static string BuildDefaultName(IEnumerable<string> 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]);
}
/// <summary>
/// Generates a random password that is never used for authentication.
/// </summary>
/// <returns>A random password string.</returns>
private static string GenerateUnusedPassword()
=> Convert.ToBase64String(RandomNumberGenerator.GetBytes(48));
/// <summary>
/// Sets library access on the shared account.
/// </summary>
/// <param name="sharedUserId">The shared account.</param>
/// <param name="enableAllFolders">Whether to grant access to every library.</param>
/// <param name="enabledFolders">The explicit library list when not granting all.</param>
/// <returns>A task representing the update.</returns>
private async Task ApplyLibraryAccessAsync(
Guid sharedUserId,
bool enableAllFolders,
IReadOnlyList<Guid>? 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);
}
}
@@ -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;
/// <summary>
/// Keeps group membership consistent with the set of users that actually exist.
/// </summary>
/// <remarks>
/// 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 <see cref="GroupService.GetEligibleMembers"/>, so this is about keeping
/// stored configuration tidy and disabling groups that have fallen below two members.
/// </remarks>
public sealed class UserLifecycleService : IHostedService
{
private readonly IUserManager _userManager;
private readonly IGroupService _groupService;
private readonly ILogger<UserLifecycleService> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="UserLifecycleService"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="groupService">The group service.</param>
/// <param name="logger">The logger.</param>
public UserLifecycleService(
IUserManager userManager,
IGroupService groupService,
ILogger<UserLifecycleService> logger)
{
_userManager = userManager;
_groupService = groupService;
_logger = logger;
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>
/// Removes references to users that no longer exist.
/// </summary>
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);
}
}
}
@@ -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;
/// <summary>
/// Propagates played state from a shared account to each of its members, one way.
/// </summary>
public sealed class WatchedStateSyncService : IHostedService, IDisposable
{
private readonly IUserDataManager _userDataManager;
private readonly IUserManager _userManager;
private readonly IGroupService _groupService;
private readonly ILogger<WatchedStateSyncService> _logger;
private bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="WatchedStateSyncService"/> class.
/// </summary>
/// <param name="userDataManager">The user data manager.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="groupService">The group service.</param>
/// <param name="logger">The logger.</param>
public WatchedStateSyncService(
IUserDataManager userDataManager,
IUserManager userManager,
IGroupService groupService,
ILogger<WatchedStateSyncService> logger)
{
_userDataManager = userDataManager;
_userManager = userManager;
_groupService = groupService;
_logger = logger;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
_userDataManager.UserDataSaved += OnUserDataSaved;
_logger.LogInformation("Watched Together sync started");
return Task.CompletedTask;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
_userDataManager.UserDataSaved -= OnUserDataSaved;
_logger.LogInformation("Watched Together sync stopped");
return Task.CompletedTask;
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
_userDataManager.UserDataSaved -= OnUserDataSaved;
_disposed = true;
}
/// <summary>
/// Mirrors a shared account's played state onto its members.
/// </summary>
/// <remarks>
/// 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
/// <c>Played</c> equality check below suppresses redundant writes on top of that.
/// </remarks>
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);
}
}
}
}
+219 -345
View File
@@ -1,415 +1,289 @@
# So you want to make a Jellyfin plugin <h1 align="center">Watched Together</h1>
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. <p align="center">
A Jellyfin plugin that lets several people share one viewing account,
while everyone's watched list stays their own.
</p>
## 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.
**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.
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 -i /path/to/templatefolder 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
``` ```
- Run this command then skip to step 4 ### 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 new Jellyfin-plugin -name MyPlugin ^(?!\s)[\w \-'._@+]+(?<!\s)$
``` ```
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. So `alice+bob` is ambiguous in principle — it could mean the group [`alice`, `bob`], or a single
real user literally named `alice+bob`.
## 1. Initialize Your Project In practice the ambiguity resolves itself: **Jellyfin only consults this plugin when no local user
matches the typed name.** A real account named `alice+bob` is found first and logs in normally,
never reaching the splitting logic. The group interpretation is only ever tried for a name that
belongs to nobody.
Make a new dotnet standard project with the following command, it will make a directory for itself. If you would rather avoid the situation entirely, change the separator to `_` or `-` in settings,
or switch auto-creation off and provision groups from the dashboard instead.
### Membership is stored as user IDs, not re-parsed from the name
Once a group exists, its membership lives in plugin configuration as a **list of user IDs**, keyed
by the shared account's ID. That list is authoritative and **nothing at runtime parses the username
again** — so you can freely rename a shared account to `Movie Night` and everything keeps working.
The name is only ever read at the moment of creation.
### Authentication
The shared account's `AuthenticationProviderId` points at this plugin, so Jellyfin routes only these
accounts to it. On login the plugin walks the member list and checks the submitted password against
each member's **live stored hash**, using Jellyfin's own `ICryptoProvider`.
Two consequences worth knowing:
- **No duplicated credentials.** There is no second copy of anyone's password anywhere. When a
member changes their password, the change takes effect immediately.
- **No lockout side effects.** The plugin deliberately does *not* re-enter Jellyfin's normal
`AuthenticateUser` flow. Doing so would trip every member's failed-attempt counter each time a
*different* member's password happened to be the one that matched, eventually locking out
members who did nothing wrong.
### Watched-state sync
The plugin subscribes to `UserDataSaved` and filters tightly: only `PlaybackFinished`,
`TogglePlayed` and `Import` are acted on, so the constant stream of progress updates during playback
is ignored.
No feedback loop is possible: writing to a member raises the event again with *that member's* ID,
which is not a shared account, so the handler stops immediately.
---
## Installation
### From the plugin repository
Add this repository URL in **Dashboard → Plugins → Repositories**:
``` ```
dotnet new classlib -f net9.0 -n MyJellyfinPlugin https://gitea.tourolle.paris/dtourolle/WatchedTogether/raw/branch/master/manifest.json
``` ```
Now add the Jellyfin shared libraries. Then install **Watched Together** from the catalogue and restart Jellyfin.
``` ### Manual
dotnet add package Jellyfin.Model
dotnet add package Jellyfin.Controller
```
You have an autogenerated Class1.cs file. You won't be needing this, so go ahead and delete it. Download the release `.zip`, extract it into a `WatchedTogether` folder inside your Jellyfin
`plugins` directory, and restart the server.
Navigate to the csproj that was generated, and ensure that you modify the package references to exclude assets, so that unnecessary files aren't copied over. ---
Skipping this step will prevent your plugin from registering correctly.
```
<ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="10.11.3">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="Jellyfin.Model" Version="10.11.3">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
</ItemGroup>
```
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 ## Setting up a group
There are a few mandatory classes you'll need for a plugin so we need to make them. ### The quick way: just log in
### PluginConfiguration On the shared device, at the Jellyfin login screen:
Create a folder named "Configuration", and a PluginConfiguration.cs file inside. - **Username:** `alice+bob` (the members' usernames, joined with `+`)
- **Password:** your own
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` 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`.
It should look something like the following: ### The dashboard way
```c#
using MediaBrowser.Model.Plugins;
namespace MyJellyfinPlugin.Configuration; If you would rather provision groups explicitly — or you have turned auto-creation off:
class PluginConfiguration : BasePluginConfiguration
{
} 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**.
### Plugin Either way, a new user appears in your user list and can be renamed like any other.
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<PluginConfiguration>` ### Per-group options
It should look something like the following: | Option | Default | Meaning |
```c# | --- | --- | --- |
using MediaBrowser.Common.Plugins; | 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. |
using MyJellyfinPlugin.Configuration; | 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. |
namespace MyJellyfinPlugin; ### Plugin settings
class Plugin : BasePlugin<PluginConfiguration> | 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. |
} ---
```
Note: If you called your PluginConfiguration class something different, you need to put that between the <> ## Security notes
### Implement Required Properties Please read this before granting a shared account broad library access.
The Plugin class needs a few properties implemented before it can work correctly. - **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.
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# ## Compatibility
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer){}
public override string Name => throw new System.NotImplementedException();
public override Guid Id => Guid.Parse("");
```
## 3. Customize Plugin Information | | |
| --- | --- |
| Target ABI | Jellyfin **10.11.x** |
| Framework | .NET 9 |
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 Verified against the 10.11.5 SDK: `IAuthenticationProvider` + `IRequiresResolvedUser`,
`ICryptoProvider.Verify`, `IUserDataManager.UserDataSaved`, and a 255-character username limit.
- **Windows Users**: you can use the Powershell command `New-Guid`, `[guid]::NewGuid()` or the Visual Studio GUID generator 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.
- **Linux and OS X Users**: you can use the Powershell Core command `New-Guid` or this command from your shell of choice: 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 ```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}' docker run --rm -v "$PWD":/src -w /src mcr.microsoft.com/dotnet/sdk:9.0 \
dotnet test Jellyfin.Plugin.WatchedTogether.sln -c Release
``` ```
or Or natively, with the .NET 9 SDK installed:
```bash ```bash
uuidgen dotnet build Jellyfin.Plugin.WatchedTogether.sln -c Release
dotnet test Jellyfin.Plugin.WatchedTogether.sln -c Release
``` ```
- Place that guid inside the `Guid.Parse("")` quotes to define your plugin's ID. To produce an installable plugin zip:
## 4. Adding Functionality ```bash
jprm plugin build .
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
``` ```
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: | Workflow | Trigger | Does |
On this section we will explain how to set up our solution to enable debugging before the server starts. | --- | --- | --- |
| `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... All three run in the builder image defined by [Dockerfile.builder](Dockerfile.builder):
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'
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 .
The only thing left to do is to compile the project as it is specified a few lines above and you are done. docker push gitea.tourolle.paris/dtourolle/watchedtogether-builder:latest
### 6.b Automate the Setup on Visual Studio Code
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 ## License
{
// 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}",
}
]
}
``` GPL-3.0. See [LICENSE](LICENSE).
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.
+21 -10
View File
@@ -1,16 +1,27 @@
--- ---
name: "Template" name: "Watched Together"
guid: "eb5d7894-8eef-4b36-aa6f-5d124e828ce1" guid: "aa3288a0-e8c1-43e2-8045-8c3411142a5b"
version: "1.0.0.0" version: "1.0.0.0"
targetAbi: "10.9.0.0" targetAbi: "10.11.0.0"
framework: "net8.0" framework: "net9.0"
overview: "Short description about your plugin" overview: "One shared login for several people; watched state flows back to each member's own account"
description: > description: >
This is a longer description that can span more than one Watched Together lets several users share a single viewing account. Any member's
line and include details about your plugin. 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" category: "General"
owner: "jellyfin" owner: "dtourolle"
artifacts: 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: >
changelog Initial release: provisioned shared accounts, multi-password authentication,
and one-way played-state sync to members.
+11
View File
@@ -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": []
}
]