Files
WatchedTogether/Jellyfin.Plugin.WatchedTogether/Controllers/WatchedTogetherController.cs
T
dtourolleandClaude Opus 5 27cd2a3d37 Inherit parental restrictions on shared accounts, with a chosen rating cap
A shared account previously inherited its members' library access but
none of their content restrictions, so a child could log into "alice+kid"
with their own password and get around their own rating cap.

The shared account now gets the strictest member's parental rating,
unrated-item block, blocked tags and allowed tags, recomputed at
creation, on membership change and at startup. An admin can raise the
rating cap on a slider between the strictest and the loosest member;
unrated and tag rules stay strictest-wins.

What makes raising the cap safe is the unlock rule: after a member's
password matches, both users' live policies are compared and the login
is refused if the account is looser than the member on any field. So
raising the cap above the child's rating means the child's password no
longer opens the account, while the parent's still does. The same rule
bounds the slider - past the loosest member nobody could unlock the
account - so a chosen cap is clamped back into range whenever applied.

Allowed tags need care: Jellyfin reads an empty list as "no whitelist",
so an empty intersection of members' whitelists is written as a sentinel
tag no item carries. Access schedules and channels are not inherited yet.

The shared account is never an administrator. Groups created at the
login screen always inherit and are restricted before the first session
exists. The dashboard shows each member's cap, who a chosen cap shuts
out, and the restrictions in effect, and gains a per-group edit form for
the sync options.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-19 12:30:50 +02:00

224 lines
8.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
using Jellyfin.Plugin.WatchedTogether.Compat;
using Jellyfin.Plugin.WatchedTogether.Configuration;
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 IRestrictionService _restrictionService;
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="restrictionService">The content restriction service.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="logger">The logger.</param>
public WatchedTogetherController(
IProvisioningService provisioningService,
IRestrictionService restrictionService,
IUserManager userManager,
ILogger<WatchedTogetherController> logger)
{
_provisioningService = provisioningService;
_restrictionService = restrictionService;
_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>());
}
return Ok(config.Groups.Select(ToDto).ToList());
}
/// <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.GetAllUsers()
.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).ConfigureAwait(false);
return Ok(ToDto(group));
}
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,
request.InheritParentalRating,
request.ParentalRatingCap).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);
}
}
/// <summary>
/// Resolves a stored group against current user records, including the restrictions its
/// shared account actually carries right now.
/// </summary>
/// <param name="group">The stored group.</param>
/// <returns>The group as the dashboard shows it.</returns>
private GroupDto ToDto(SharedGroup group)
{
var sharedUser = _userManager.GetUserById(group.SharedUserId);
var range = _restrictionService.GetRatingRange(group.MemberUserIds);
return new GroupDto
{
SharedUserId = group.SharedUserId,
SharedUsername = sharedUser?.Username ?? "(deleted)",
SyncUnwatched = group.SyncUnwatched,
SyncPlayCount = group.SyncPlayCount,
IsDisabled = group.IsDisabled,
InheritParentalRating = group.InheritParentalRating,
ParentalRatingCap = group.ParentalRatingCap,
StrictestMemberRating = range.Strictest,
LoosestMemberRating = range.Loosest,
Restrictions = sharedUser is null ? null : ToDto(ContentRestrictions.FromUser(sharedUser)),
Members = group.MemberUserIds.Select(id =>
{
var member = _userManager.GetUserById(id);
return new MemberDto
{
UserId = id,
Username = member?.Username ?? "(deleted)",
MaxParentalRating = member is null ? 0 : member.MaxParentalRatingScore
};
}).ToList()
};
}
private static RestrictionsDto ToDto(ContentRestrictions restrictions)
=> new()
{
MaxParentalRating = restrictions.MaxParentalRatingScore,
MaxParentalSubRating = restrictions.MaxParentalRatingSubScore,
BlockUnratedItems = restrictions.BlockUnratedItems.Select(u => u.ToString()).OrderBy(u => u, StringComparer.Ordinal).ToList(),
BlockedTags = restrictions.BlockedTags.OrderBy(t => t, StringComparer.OrdinalIgnoreCase).ToList(),
AllowedTags = (restrictions.AllowedTags ?? Enumerable.Empty<string>()).OrderBy(t => t, StringComparer.OrdinalIgnoreCase).ToList(),
AllowsNothing = restrictions.HasAllowedTags && restrictions.AllowedTags!.Count == 0
};
}