Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
512633d49b
|
||
|
|
4b91c380a1
|
||
|
|
93036bae89
|
||
|
|
28b6244a17
|
||
|
|
9e38c98da2
|
||
|
|
ea28ad29ac
|
||
|
|
dea2569fd7
|
||
|
|
9c89852e97
|
||
|
|
f6083a5839
|
||
|
|
7f357cb46c
|
||
|
|
383b90d9b8
|
||
|
|
f5869c2319
|
||
|
|
8618ee2573
|
||
|
|
dba6a8ecef
|
||
|
|
66593e9da2
|
||
|
|
1cc93c5250
|
||
|
|
d161e26cd7
|
||
|
|
2a62583c3c
|
@@ -0,0 +1,134 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: build-${{ gitea.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# build.yaml is the source of truth for the plugin version.
|
||||
# A version without a matching tag on main gets released.
|
||||
- name: Read version
|
||||
id: version
|
||||
run: |
|
||||
version="$(sed -n 's/^version:[[:space:]]*"\{0,1\}\([0-9][0-9.]*\)"\{0,1\}[[:space:]]*$/\1/p' build.yaml)"
|
||||
if [ -z "$version" ]; then
|
||||
echo "::error file=build.yaml::could not read the version"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
props="$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props)"
|
||||
if [ "$props" != "$version" ]; then
|
||||
echo "::error::build.yaml says $version but Directory.Build.props says $props"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
tag="v$version"
|
||||
release=false
|
||||
if [ "$GITHUB_EVENT_NAME" != "pull_request" ] && [ "$GITHUB_REF" = "refs/heads/main" ]; then
|
||||
if [ -z "$(git ls-remote --tags origin "refs/tags/$tag")" ]; then
|
||||
release=true
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
echo "release=$release" >> "$GITHUB_OUTPUT"
|
||||
echo "Version $version, tag $tag, release: $release"
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 9.0.x
|
||||
|
||||
- name: Build
|
||||
run: dotnet build -c Release
|
||||
|
||||
- name: Test
|
||||
run: dotnet test -c Release --no-build
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
pip install jprm
|
||||
mkdir -p artifacts
|
||||
jprm plugin build . --output artifacts --version "${{ steps.version.outputs.version }}"
|
||||
ls -l artifacts
|
||||
|
||||
# manifest.json in the source tree is the plugin repository users install from.
|
||||
# Add this version to it; it is committed back once the release exists.
|
||||
- name: Update repository manifest
|
||||
if: steps.version.outputs.release == 'true'
|
||||
env:
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
mkdir -p repo
|
||||
cp manifest.json repo/manifest.json
|
||||
|
||||
zip="$(ls artifacts/*.zip)"
|
||||
jprm repo add \
|
||||
--plugin-url "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/download/$TAG/$(basename "$zip")" \
|
||||
repo "$zip"
|
||||
cp repo/manifest.json artifacts/manifest.json
|
||||
cat artifacts/manifest.json
|
||||
|
||||
- name: Create tag and release
|
||||
if: steps.version.outputs.release == 'true'
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
|
||||
sed -n '/^changelog:/,$p' build.yaml | sed '1d; s/^ //' > notes.md
|
||||
|
||||
python3 - > release.json <<'PY'
|
||||
import json, os
|
||||
tag = os.environ["TAG"]
|
||||
print(json.dumps({
|
||||
"tag_name": tag,
|
||||
"target_commitish": os.environ["GITHUB_SHA"],
|
||||
"name": "Herald " + tag[1:],
|
||||
"body": open("notes.md", encoding="utf-8").read(),
|
||||
}))
|
||||
PY
|
||||
|
||||
id="$(curl -fsS -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
--data @release.json "$api/releases" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')"
|
||||
|
||||
for file in artifacts/*.zip artifacts/manifest.json; do
|
||||
curl -fsS -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$file" "$api/releases/$id/assets?name=$(basename "$file")" > /dev/null
|
||||
echo "Attached $(basename "$file")"
|
||||
done
|
||||
|
||||
- name: Commit repository manifest
|
||||
if: steps.version.outputs.release == 'true'
|
||||
env:
|
||||
TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
run: |
|
||||
cp artifacts/manifest.json manifest.json
|
||||
if git diff --quiet -- manifest.json; then
|
||||
echo "manifest.json is already up to date"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "$GITHUB_ACTOR"
|
||||
git config user.email "$GITHUB_ACTOR@noreply.${GITHUB_SERVER_URL#*://}"
|
||||
git add manifest.json
|
||||
git commit -m "chore: add $TAG to the plugin manifest [skip ci]"
|
||||
git push "${GITHUB_SERVER_URL%%://*}://x-access-token:$TOKEN@${GITHUB_SERVER_URL#*://}/$GITHUB_REPOSITORY.git" HEAD:main
|
||||
@@ -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
|
||||
@@ -0,0 +1,61 @@
|
||||
# Decisions
|
||||
|
||||
One line per decision, with the reason.
|
||||
|
||||
## Target and build
|
||||
|
||||
- Target Jellyfin **10.11.11** (`Jellyfin.Controller` / `Jellyfin.Model` 10.11.11, `net9.0`): it is the last 10.11 release on NuGet; the nuspec of that package lists `net9.0` as its only framework. Versions live in `Directory.Build.props`.
|
||||
- `targetAbi` is `10.11.0.0`: the plugin only uses APIs that exist across 10.11, so it should not be pinned to the patch release it was compiled against.
|
||||
- Removed the template's `.github` workflows and Renovate preset: they call reusable workflows and secrets of the Jellyfin organisation and cannot run elsewhere. Replaced by one self-contained workflow for Gitea Actions in `.gitea/workflows`; it talks to the Gitea API with `curl`, so it needs no forge-specific CLI on the runner.
|
||||
- Releases are driven by the version, not by hand-made tags: a push to `main` whose `build.yaml` version has no `v<version>` tag is tagged and released by the workflow. The plugin repository is `manifest.json` in the source tree, installed through its raw link on `main`; the workflow adds each release to it and commits the file back (`[skip ci]`), so the install URL does not depend on a release asset.
|
||||
- Removed the template's `.vscode` folder: it assumes a local checkout of the Jellyfin server and web client next to the repo.
|
||||
- No analyzer warnings are suppressed project-wide. The only suppressions are three `CA2100` pragmas in `Storage/` where a command text is assigned from a constant string, which the analyzer cannot see through a helper.
|
||||
- The test project does not reference the StyleCop/`AllEnabledByDefault` analyzer set: XML docs and naming rules on test methods add noise without value. It still builds with warnings as errors.
|
||||
|
||||
## Storage
|
||||
|
||||
- **SQLite via `Microsoft.Data.Sqlite`**, not JSON files. Jellyfin 10.11.11 ships `Microsoft.Data.Sqlite` 9.0.11 itself; the plugin references exactly that version with `ExcludeAssets="runtime;native"`, so no SQLite DLL (managed or native) ends up in the plugin folder and the host's copy is used. Verified in the 10.11.11 container: the plugin zip contains only `Jellyfin.Plugin.Herald.dll`, and the database is created and migrated on first use.
|
||||
- Database path is `<data dir>/herald/herald.db` (`IApplicationPaths.DataPath`), not `BasePlugin.DataFolderPath`: the latter resolves to a folder inside `plugins/` whose name can include the plugin version, so data would be left behind on every update.
|
||||
- Writes go through one lock and one transaction each; the file runs in WAL mode so reads are not blocked. Schema changes are numbered scripts tracked in `PRAGMA user_version`.
|
||||
- A database newer than the plugin (downgrade) fails loudly instead of being opened.
|
||||
|
||||
## Notices
|
||||
|
||||
- `Target` is an object `{ AllUsers, UserIds }`: clearer than "empty list means everyone", which would turn a notice for one deleted user into a notice for all.
|
||||
- Editing a notice does not show it again. Only "Re-show to everyone" bumps `Revision`: fixing a typo should not interrupt everybody.
|
||||
- The first response of a user to a revision is kept; later ones for the same revision are ignored. This keeps the record of what the user actually did.
|
||||
- `Ack` with an outdated revision returns `409`, for a missing, disabled or not-addressed notice `404`, and `Dismissed` on a must-accept notice `400`.
|
||||
- The acknowledgement report covers the current revision only. Older rounds stay in the database but are not exposed; nobody asked for history.
|
||||
- The pending-users list in the report only contains users that still exist. Responses of deleted users are kept and shown without a name.
|
||||
- `GET /Herald/Notices/Pending` with an API key (no user) returns an empty list rather than an error.
|
||||
- Body format is the Markdown subset from the task (bold, italic, links, lists) rendered in the browser with DOM nodes; the server stores the text as typed. Links are limited to `http`, `https` and `mailto`.
|
||||
- The wait before accepting (`AcceptDelaySeconds`, 0 to 600) is per notice and only kept for must-accept notices. It is enforced by the client script, not by the `Ack` endpoint: the server does not know when a popup appeared, and must-accept is a record of consent, not a gate. The countdown pauses while the tab is hidden.
|
||||
- Notice titles and ids are logged. Bodies and user names are not.
|
||||
|
||||
## Client injection
|
||||
|
||||
- Registration with File Transformation is done purely by reflection, including building the payload: the `JObject` is created by calling `Parse` on the parameter type of `RegisterTransformation`, so the plugin has no Newtonsoft reference of its own.
|
||||
- The file pattern is the literal `index.html`, the same string every other plugin registers. File Transformation groups callbacks by pattern string and, for a request, runs only the group whose key equals the requested path; a regex fallback is used only when no key matches exactly. The earlier anchored `^index\.html$` was therefore never called once MediaBar (or any plugin using `index.html`) was installed. Found by reproducing a server with MediaBar and Jellyfin Enhanced.
|
||||
- As a regular expression `index.html` also matches script chunks such as `session-login-index-html.<hash>.chunk.js`, so those are handed to the callback too. The transformer returns anything that is not an HTML page (`<html` and `</body>` present) unchanged.
|
||||
- The script tag uses the relative URL `../Herald/client.js` so it keeps working behind a base URL.
|
||||
- `GET /Herald/client.js` is anonymous: a `<script>` tag cannot send Jellyfin's auth header, and the file holds nothing secret.
|
||||
- Jellyfin 10.11 has **no "Custom HTML" setting** (branding only offers custom CSS, a login disclaimer and the splash screen; checked against `BrandingOptions`). The documented manual fallbacks are therefore the JavaScript Injector plugin and editing `index.html`.
|
||||
- Login and user switches are detected by comparing `ApiClient.getCurrentUserId()` on a 3 s local timer. That costs no request; the server is only asked after a change of user and then at most every 10 minutes. jellyfin-web's own login events are not reachable from an injected script in a stable way.
|
||||
- The modal reuses jellyfin-web's `dialog`, `raised`, `button-submit` and `emby-button` classes so the active theme colours it; own CSS only handles layout.
|
||||
|
||||
## Admin UI
|
||||
|
||||
- The config page is flagged `EnableInMainMenu`, so it has its own entry in the dashboard sidebar under "Plugins". Jellyfin 10.11 draws a fixed icon there; `MenuIcon` is set for versions that honour it.
|
||||
|
||||
## Watch-time stats
|
||||
|
||||
- Time is measured on the **server clock between two reports** of the same playback, not from playback positions: a seek changes the position by minutes without anyone watching, and position deltas also break with playback speed.
|
||||
- Each delta is capped at 60 s; a playback without a report for 5 minutes counts as closed and the gap adds nothing.
|
||||
- Progress events flagged `IsAutomated` are ignored. The server generates those itself on a timer while a client is silent, so they say nothing about someone still watching.
|
||||
- A playback is keyed by session id plus item id. Switching items without a stop report simply lets the old entry time out.
|
||||
- `PlayCount` counts playback start events. A progress report for an unknown playback (server restarted mid-film) is tracked but not counted as a play.
|
||||
- A delta that crosses local midnight is split between both days.
|
||||
- Stats for deleted users stay until they age out and are returned with `UserName: null`.
|
||||
- `GET /Herald/Stats` returns `WatchedSeconds` next to the requested hours: rounded hours are useless for short sessions.
|
||||
- No chart. A hairline under the 30-day value shows each user's share of the busiest user's time; that is all the table needs.
|
||||
- The cleanup task is discovered by Jellyfin as an `IScheduledTask` (daily at 03:30) and is not registered in DI, which is how Jellyfin 10.11 finds tasks.
|
||||
@@ -7,8 +7,8 @@
|
||||
<!-- Microsoft.Data.Sqlite version shipped with that Jellyfin release (Directory.Packages.props upstream). -->
|
||||
<JellyfinSqliteVersion>9.0.11</JellyfinSqliteVersion>
|
||||
|
||||
<Version>1.0.0.0</Version>
|
||||
<AssemblyVersion>1.0.0.0</AssemblyVersion>
|
||||
<FileVersion>1.0.0.0</FileVersion>
|
||||
<Version>1.1.0.0</Version>
|
||||
<AssemblyVersion>1.1.0.0</AssemblyVersion>
|
||||
<FileVersion>1.1.0.0</FileVersion>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
using Jellyfin.Plugin.Herald.Injection;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
public class IndexHtmlTransformerTests
|
||||
{
|
||||
private const string Page = "<html><head></head><body><div id=\"reactRoot\"></div></body></html>";
|
||||
|
||||
[Fact]
|
||||
public void Inject_AddsTheScriptBeforeTheClosingBodyTag()
|
||||
{
|
||||
var result = IndexHtmlTransformer.Inject(Page);
|
||||
|
||||
Assert.EndsWith(IndexHtmlTransformer.ScriptTag + "</body></html>", result, StringComparison.Ordinal);
|
||||
Assert.Contains("src=\"../Herald/client.js?v=", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Inject_IsIdempotent()
|
||||
{
|
||||
var once = IndexHtmlTransformer.Inject(Page);
|
||||
|
||||
Assert.Equal(once, IndexHtmlTransformer.Inject(once));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Inject_LeavesContentWithoutABodyTagAlone()
|
||||
{
|
||||
const string Script = "(self.webpackChunk=self.webpackChunk||[]).push([[17244],{}]);";
|
||||
|
||||
Assert.Equal(Script, IndexHtmlTransformer.Inject(Script));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Inject_LeavesScriptsThatMentionABodyTagAlone()
|
||||
{
|
||||
const string Script = "(self.webpackChunk=self.webpackChunk||[]).push([[17244],{t:\"<div></div></body>\"}]);";
|
||||
|
||||
Assert.Equal(Script, IndexHtmlTransformer.Inject(Script));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Inject_KeepsTagsOtherPluginsAdded()
|
||||
{
|
||||
const string Other = "<script defer src=\"../MediaBar/slideshowpure.js\"></script>";
|
||||
var page = Page.Replace("</body>", Other + "</body>", StringComparison.Ordinal);
|
||||
|
||||
var result = IndexHtmlTransformer.Inject(page);
|
||||
|
||||
Assert.Contains(Other + IndexHtmlTransformer.ScriptTag + "</body>", result, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Transform_HandlesAnEmptyPayload()
|
||||
{
|
||||
Assert.Equal(string.Empty, IndexHtmlTransformer.Transform(new IndexHtmlPayload()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Transform_InjectsIntoThePayloadContents()
|
||||
{
|
||||
var result = IndexHtmlTransformer.Transform(new IndexHtmlPayload { Contents = Page });
|
||||
|
||||
Assert.Contains(IndexHtmlTransformer.Marker, result, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>$(JellyfinTargetFramework)</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" PrivateAssets="All" />
|
||||
<!-- The plugin leaves these to the Jellyfin host; the tests have to bring them along. -->
|
||||
<PackageReference Include="Jellyfin.Controller" Version="$(JellyfinVersion)" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="$(JellyfinSqliteVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Jellyfin.Plugin.Herald\Jellyfin.Plugin.Herald.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A clock the tests move by hand.
|
||||
/// </summary>
|
||||
public sealed class ManualTimeProvider : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now;
|
||||
|
||||
public ManualTimeProvider(DateTimeOffset now, TimeZoneInfo? zone = null)
|
||||
{
|
||||
_now = now;
|
||||
LocalTimeZone = zone ?? TimeZoneInfo.Utc;
|
||||
}
|
||||
|
||||
public override TimeZoneInfo LocalTimeZone { get; }
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
|
||||
public void Set(DateTimeOffset now) => _now = now;
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Jellyfin.Plugin.Herald.Notices;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
public class NoticeRulesTests
|
||||
{
|
||||
private static readonly Guid _alice = Guid.NewGuid();
|
||||
private static readonly Guid _bob = Guid.NewGuid();
|
||||
|
||||
private static Notice Notice(Action<Notice>? configure = null)
|
||||
{
|
||||
var notice = new Notice
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Title = "Maintenance",
|
||||
Body = "Saturday night.",
|
||||
CreatedAt = new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)
|
||||
};
|
||||
configure?.Invoke(notice);
|
||||
return notice;
|
||||
}
|
||||
|
||||
private static NoticeAck Ack(Notice notice, Guid userId, int? revision = null) => new()
|
||||
{
|
||||
NoticeId = notice.Id,
|
||||
UserId = userId,
|
||||
Revision = revision ?? notice.Revision,
|
||||
Action = AckAction.Dismissed
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Pending_WhenNeverAcknowledged()
|
||||
{
|
||||
Assert.True(NoticeRules.IsPending(Notice(), _alice, []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotPending_AfterAcknowledgingCurrentRevision()
|
||||
{
|
||||
var notice = Notice();
|
||||
|
||||
Assert.False(NoticeRules.IsPending(notice, _alice, [Ack(notice, _alice)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pending_AgainAfterRevisionBump()
|
||||
{
|
||||
var notice = Notice();
|
||||
var ack = Ack(notice, _alice);
|
||||
notice.Revision++;
|
||||
|
||||
Assert.True(NoticeRules.IsPending(notice, _alice, [ack]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pending_IgnoresOtherUsersAndOtherNotices()
|
||||
{
|
||||
var notice = Notice();
|
||||
var other = Notice();
|
||||
|
||||
Assert.True(NoticeRules.IsPending(notice, _alice, [Ack(notice, _bob), Ack(other, _alice)]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NotPending_WhenDisabled()
|
||||
{
|
||||
Assert.False(NoticeRules.IsPending(Notice(n => n.Enabled = false), _alice, []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Targeting_OnlyListedUsersSeeTheNotice()
|
||||
{
|
||||
var notice = Notice(n => n.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice] });
|
||||
|
||||
Assert.True(NoticeRules.IsPending(notice, _alice, []));
|
||||
Assert.False(NoticeRules.IsPending(notice, _bob, []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Targeting_AllUsersWinsOverALeftoverList()
|
||||
{
|
||||
var notice = Notice(n => n.Target = new NoticeTarget { AllUsers = true, UserIds = [_alice] });
|
||||
|
||||
Assert.True(NoticeRules.IsPending(notice, _bob, []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectPending_ReturnsOldestFirst()
|
||||
{
|
||||
var newest = Notice(n => n.CreatedAt = new DateTime(2026, 3, 3, 0, 0, 0, DateTimeKind.Utc));
|
||||
var oldest = Notice(n => n.CreatedAt = new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc));
|
||||
var middle = Notice(n => n.CreatedAt = new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc));
|
||||
var done = Notice();
|
||||
|
||||
var pending = NoticeRules.SelectPending([newest, oldest, done, middle], _alice, [Ack(done, _alice)]);
|
||||
|
||||
Assert.Equal([oldest.Id, middle.Id, newest.Id], pending.Select(n => n.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ack_DismissIsRejectedWhenAcceptIsRequired()
|
||||
{
|
||||
var notice = Notice(n => n.RequireAccept = true);
|
||||
|
||||
Assert.Equal(AckResult.AcceptRequired, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Dismissed));
|
||||
Assert.Equal(AckResult.Ok, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Accepted));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ack_BothActionsAreFineWithoutRequireAccept()
|
||||
{
|
||||
var notice = Notice();
|
||||
|
||||
Assert.Equal(AckResult.Ok, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Dismissed));
|
||||
Assert.Equal(AckResult.Ok, NoticeRules.ValidateAck(notice, _alice, notice.Revision, AckAction.Accepted));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ack_OutdatedRevisionIsRejected()
|
||||
{
|
||||
var notice = Notice(n => n.Revision = 3);
|
||||
|
||||
Assert.Equal(AckResult.RevisionMismatch, NoticeRules.ValidateAck(notice, _alice, 2, AckAction.Accepted));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ack_UnknownDisabledOrUntargetedNoticeIsNotFound()
|
||||
{
|
||||
var disabled = Notice(n => n.Enabled = false);
|
||||
var notForBob = Notice(n => n.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice] });
|
||||
|
||||
Assert.Equal(AckResult.NotFound, NoticeRules.ValidateAck(null, _alice, 1, AckAction.Accepted));
|
||||
Assert.Equal(AckResult.NotFound, NoticeRules.ValidateAck(disabled, _alice, 1, AckAction.Accepted));
|
||||
Assert.Equal(AckResult.NotFound, NoticeRules.ValidateAck(notForBob, _bob, 1, AckAction.Accepted));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Draft_NeedsATitle(string? title)
|
||||
{
|
||||
Assert.NotNull(NoticeRules.ValidateDraft(new NoticeDraft { Title = title }));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(-1, false)]
|
||||
[InlineData(0, true)]
|
||||
[InlineData(600, true)]
|
||||
[InlineData(601, false)]
|
||||
public void Draft_AcceptDelayHasToBeInRange(int seconds, bool valid)
|
||||
{
|
||||
var draft = new NoticeDraft { Title = "Hi", RequireAccept = true, AcceptDelaySeconds = seconds };
|
||||
|
||||
Assert.Equal(valid, NoticeRules.ValidateDraft(draft) is null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Draft_SelectedUsersNeedAtLeastOneUser()
|
||||
{
|
||||
var draft = new NoticeDraft { Title = "Hi", Target = new NoticeTarget { AllUsers = false } };
|
||||
|
||||
Assert.NotNull(NoticeRules.ValidateDraft(draft));
|
||||
Assert.Null(NoticeRules.ValidateDraft(new NoticeDraft { Title = "Hi" }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using Jellyfin.Plugin.Herald.Notices;
|
||||
using Jellyfin.Plugin.Herald.Storage;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
public sealed class NoticeServiceTests : IDisposable
|
||||
{
|
||||
private static readonly Guid _alice = Guid.NewGuid();
|
||||
private static readonly Guid _bob = Guid.NewGuid();
|
||||
private static readonly Dictionary<Guid, string> _userNames = new() { [_alice] = "alice", [_bob] = "bob" };
|
||||
|
||||
private readonly TempDatabase _temp = new();
|
||||
private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 3, 10, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly NoticeService _service;
|
||||
|
||||
public NoticeServiceTests()
|
||||
{
|
||||
_service = new NoticeService(new SqliteNoticeStore(_temp.Database), _clock, NullLogger<NoticeService>.Instance);
|
||||
}
|
||||
|
||||
public void Dispose() => _temp.Dispose();
|
||||
|
||||
private Notice Create(string title, Action<NoticeDraft>? configure = null)
|
||||
{
|
||||
var draft = new NoticeDraft { Title = title, Body = "Body" };
|
||||
configure?.Invoke(draft);
|
||||
var notice = _service.Create(draft);
|
||||
_clock.Advance(TimeSpan.FromMinutes(1));
|
||||
return notice;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AcceptDelay_IsStoredForMustAcceptNotices()
|
||||
{
|
||||
var created = Create("Terms", d =>
|
||||
{
|
||||
d.RequireAccept = true;
|
||||
d.AcceptDelaySeconds = 15;
|
||||
});
|
||||
|
||||
Assert.Equal(15, _service.Get(created.Id)!.AcceptDelaySeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AcceptDelay_IsDroppedWithoutRequireAccept()
|
||||
{
|
||||
var created = Create("Info", d => d.AcceptDelaySeconds = 15);
|
||||
|
||||
Assert.Equal(0, _service.Get(created.Id)!.AcceptDelaySeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_RoundTripsThroughTheDatabase()
|
||||
{
|
||||
var created = Create(" Hello ", d =>
|
||||
{
|
||||
d.Body = "Line one\r\nLine two";
|
||||
d.RequireAccept = true;
|
||||
d.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice, _alice, _bob] };
|
||||
});
|
||||
|
||||
var loaded = _service.Get(created.Id);
|
||||
|
||||
Assert.NotNull(loaded);
|
||||
Assert.Equal("Hello", loaded.Title);
|
||||
Assert.Equal("Line one\nLine two", loaded.Body);
|
||||
Assert.True(loaded.RequireAccept);
|
||||
Assert.True(loaded.Enabled);
|
||||
Assert.False(loaded.Target.AllUsers);
|
||||
Assert.Equal([_alice, _bob], loaded.Target.UserIds);
|
||||
Assert.Equal(1, loaded.Revision);
|
||||
Assert.Equal(new DateTime(2026, 3, 10, 12, 0, 0, DateTimeKind.Utc), loaded.CreatedAt);
|
||||
Assert.Equal(DateTimeKind.Utc, loaded.CreatedAt.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pending_ShowsEachNoticeOnceOldestFirst()
|
||||
{
|
||||
var first = Create("First");
|
||||
var second = Create("Second");
|
||||
|
||||
Assert.Equal([first.Id, second.Id], _service.GetPending(_alice).Select(n => n.Id));
|
||||
|
||||
Assert.Equal(AckResult.Ok, _service.Acknowledge(_alice, first.Id, 1, AckAction.Dismissed));
|
||||
|
||||
Assert.Equal([second.Id], _service.GetPending(_alice).Select(n => n.Id));
|
||||
Assert.Equal(2, _service.GetPending(_bob).Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reshow_BringsTheNoticeBackForEveryone()
|
||||
{
|
||||
var notice = Create("Rules");
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted);
|
||||
Assert.Empty(_service.GetPending(_alice));
|
||||
|
||||
var bumped = _service.Reshow(notice.Id);
|
||||
|
||||
Assert.Equal(2, bumped!.Revision);
|
||||
Assert.Equal(2, Assert.Single(_service.GetPending(_alice)).Revision);
|
||||
|
||||
// The old revision can no longer be answered.
|
||||
Assert.Equal(AckResult.RevisionMismatch, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted));
|
||||
Assert.Equal(AckResult.Ok, _service.Acknowledge(_alice, notice.Id, 2, AckAction.Accepted));
|
||||
Assert.Empty(_service.GetPending(_alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Update_KeepsRevisionAndAcknowledgements()
|
||||
{
|
||||
var notice = Create("Typo");
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||
|
||||
var updated = _service.Update(notice.Id, new NoticeDraft { Title = "Fixed", Body = "Body" });
|
||||
|
||||
Assert.Equal(1, updated!.Revision);
|
||||
Assert.Equal(notice.CreatedAt, updated.CreatedAt);
|
||||
Assert.True(updated.UpdatedAt > updated.CreatedAt);
|
||||
Assert.Empty(_service.GetPending(_alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disabled_NoticeIsNotPendingAndCannotBeAnswered()
|
||||
{
|
||||
var notice = Create("Off", d => d.Enabled = false);
|
||||
|
||||
Assert.Empty(_service.GetPending(_alice));
|
||||
Assert.Equal(AckResult.NotFound, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Targeted_NoticeIsOnlyPendingForItsUsers()
|
||||
{
|
||||
var notice = Create("Just Alice", d => d.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice] });
|
||||
|
||||
Assert.Single(_service.GetPending(_alice));
|
||||
Assert.Empty(_service.GetPending(_bob));
|
||||
Assert.Equal(AckResult.NotFound, _service.Acknowledge(_bob, notice.Id, 1, AckAction.Dismissed));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequireAccept_DismissIsRejectedAndNothingIsStored()
|
||||
{
|
||||
var notice = Create("Terms", d => d.RequireAccept = true);
|
||||
|
||||
Assert.Equal(AckResult.AcceptRequired, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed));
|
||||
Assert.Single(_service.GetPending(_alice));
|
||||
|
||||
Assert.Equal(AckResult.Ok, _service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted));
|
||||
Assert.Empty(_service.GetPending(_alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Acknowledge_TwiceKeepsTheFirstResponse()
|
||||
{
|
||||
var notice = Create("Once");
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||
_clock.Advance(TimeSpan.FromHours(1));
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted);
|
||||
|
||||
var response = Assert.Single(_service.GetAckReport(notice.Id, _userNames)!.Responses);
|
||||
|
||||
Assert.Equal(AckAction.Dismissed, response.Action);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AckReport_ListsResponsesAndWhoIsStillPending()
|
||||
{
|
||||
var carol = Guid.NewGuid();
|
||||
var notice = Create("Report", d => d.Target = new NoticeTarget { AllUsers = false, UserIds = [_alice, _bob, carol] });
|
||||
var answeredAt = _clock.GetUtcNow().UtcDateTime;
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Accepted);
|
||||
|
||||
// carol was deleted in the meantime and is not part of the user list.
|
||||
var report = _service.GetAckReport(notice.Id, _userNames)!;
|
||||
|
||||
var response = Assert.Single(report.Responses);
|
||||
Assert.Equal("alice", response.UserName);
|
||||
Assert.Equal(AckAction.Accepted, response.Action);
|
||||
Assert.Equal(answeredAt, response.Timestamp);
|
||||
Assert.Equal("bob", Assert.Single(report.Pending).UserName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AckReport_OnlyCoversTheCurrentRevision()
|
||||
{
|
||||
var notice = Create("Again");
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||
_service.Reshow(notice.Id);
|
||||
|
||||
var report = _service.GetAckReport(notice.Id, _userNames)!;
|
||||
|
||||
Assert.Equal(2, report.Revision);
|
||||
Assert.Empty(report.Responses);
|
||||
Assert.Equal(["alice", "bob"], report.Pending.Select(p => p.UserName));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delete_RemovesNoticeAndAcknowledgements()
|
||||
{
|
||||
var notice = Create("Gone");
|
||||
_service.Acknowledge(_alice, notice.Id, 1, AckAction.Dismissed);
|
||||
|
||||
Assert.True(_service.Delete(notice.Id));
|
||||
Assert.False(_service.Delete(notice.Id));
|
||||
Assert.Null(_service.Get(notice.Id));
|
||||
Assert.Null(_service.GetAckReport(notice.Id, _userNames));
|
||||
Assert.Empty(new SqliteNoticeStore(_temp.Database).GetAcksByUser(_alice));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_NoticeOperationsReturnNull()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
|
||||
Assert.Null(_service.Update(id, new NoticeDraft { Title = "x" }));
|
||||
Assert.Null(_service.Reshow(id));
|
||||
Assert.Equal(AckResult.NotFound, _service.Acknowledge(_alice, id, 1, AckAction.Accepted));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using Jellyfin.Plugin.Herald.Stats;
|
||||
using Jellyfin.Plugin.Herald.Storage;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
public sealed class StatsStorageTests : IDisposable
|
||||
{
|
||||
private static readonly Guid _alice = Guid.NewGuid();
|
||||
private static readonly Guid _bob = Guid.NewGuid();
|
||||
private static readonly DateOnly _today = new(2026, 3, 10);
|
||||
|
||||
private readonly TempDatabase _temp = new();
|
||||
private readonly ManualTimeProvider _clock = new(new DateTimeOffset(2026, 3, 10, 12, 0, 0, TimeSpan.Zero));
|
||||
private readonly SqliteWatchStatsStore _store;
|
||||
private readonly StatsService _service;
|
||||
|
||||
public StatsStorageTests()
|
||||
{
|
||||
_store = new SqliteWatchStatsStore(_temp.Database);
|
||||
_service = new StatsService(_store, _clock);
|
||||
}
|
||||
|
||||
public void Dispose() => _temp.Dispose();
|
||||
|
||||
private static WatchIncrement Watched(Guid user, DateOnly date, double seconds, int plays = 0, int hour = 10)
|
||||
{
|
||||
return new WatchIncrement(user, date, seconds, plays, date.ToDateTime(new TimeOnly(hour, 0), DateTimeKind.Utc));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Add_AccumulatesIntoOneRowPerUserAndDay()
|
||||
{
|
||||
_store.Add([Watched(_alice, _today, 0, plays: 1, hour: 9)]);
|
||||
_store.Add([Watched(_alice, _today, 10, hour: 11), Watched(_alice, _today, 15.5, hour: 10)]);
|
||||
_store.Add([Watched(_bob, _today, 7, plays: 1)]);
|
||||
|
||||
var rows = _store.GetSince(_today);
|
||||
|
||||
Assert.Equal(2, rows.Count);
|
||||
var alice = Assert.Single(rows, r => r.UserId == _alice);
|
||||
Assert.Equal(25.5, alice.WatchedSeconds, 6);
|
||||
Assert.Equal(1, alice.PlayCount);
|
||||
Assert.Equal(new DateTime(2026, 3, 10, 11, 0, 0, DateTimeKind.Utc), alice.LastActivity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Summary_CoversTheRequestedDaysIncludingToday()
|
||||
{
|
||||
_store.Add(
|
||||
[
|
||||
Watched(_alice, _today, 3600, plays: 1),
|
||||
Watched(_alice, _today.AddDays(-6), 1800, plays: 2),
|
||||
Watched(_alice, _today.AddDays(-7), 7200, plays: 4),
|
||||
Watched(_alice, _today.AddDays(-29), 3600, plays: 1),
|
||||
Watched(_alice, _today.AddDays(-30), 36000, plays: 9)
|
||||
]);
|
||||
var names = new Dictionary<Guid, string> { [_alice] = "alice", [_bob] = "bob" };
|
||||
|
||||
var week = _service.GetSummary(7, names);
|
||||
var month = _service.GetSummary(30, names);
|
||||
|
||||
var aliceWeek = Assert.Single(week, s => s.UserName == "alice");
|
||||
Assert.Equal(1.5, aliceWeek.WatchedHours);
|
||||
Assert.Equal(5400, aliceWeek.WatchedSeconds);
|
||||
Assert.Equal(3, aliceWeek.PlayCount);
|
||||
|
||||
var aliceMonth = Assert.Single(month, s => s.UserName == "alice");
|
||||
Assert.Equal(4.5, aliceMonth.WatchedHours);
|
||||
Assert.Equal(8, aliceMonth.PlayCount);
|
||||
Assert.Equal(new DateTime(2026, 3, 10, 10, 0, 0, DateTimeKind.Utc), aliceMonth.LastActivity);
|
||||
|
||||
var bob = Assert.Single(month, s => s.UserName == "bob");
|
||||
Assert.Equal(0, bob.WatchedHours);
|
||||
Assert.Equal(0, bob.PlayCount);
|
||||
Assert.Null(bob.LastActivity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Summary_KeepsActivityOfDeletedUsersWithoutAName()
|
||||
{
|
||||
_store.Add([Watched(_alice, _today, 600, plays: 1)]);
|
||||
|
||||
var summary = _service.GetSummary(30, new Dictionary<Guid, string> { [_bob] = "bob" });
|
||||
|
||||
Assert.Equal(["bob", null], summary.Select(s => s.UserName));
|
||||
Assert.Equal(_alice, summary[1].UserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Summary_UsesTheServerLocalDay()
|
||||
{
|
||||
// 23:30 UTC on the 10th is already the 11th at UTC+2.
|
||||
var zone = TimeZoneInfo.CreateCustomTimeZone("test+2", TimeSpan.FromHours(2), "test+2", "test+2");
|
||||
var service = new StatsService(_store, new ManualTimeProvider(new DateTimeOffset(2026, 3, 10, 23, 30, 0, TimeSpan.Zero), zone));
|
||||
|
||||
Assert.Equal(new DateOnly(2026, 3, 11), service.Today);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cleanup_DeletesRowsOlderThanNinetyDays()
|
||||
{
|
||||
_store.Add(
|
||||
[
|
||||
Watched(_alice, _today, 10),
|
||||
Watched(_alice, _today.AddDays(-90), 10),
|
||||
Watched(_alice, _today.AddDays(-91), 10),
|
||||
Watched(_bob, _today.AddDays(-200), 10)
|
||||
]);
|
||||
|
||||
var deleted = _service.Cleanup();
|
||||
|
||||
Assert.Equal(2, deleted);
|
||||
Assert.Equal([_today.AddDays(-90), _today], _store.GetSince(DateOnly.MinValue).Select(r => r.Date));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Database_IsCreatedOnFirstUseAndMigrationsRunOnce()
|
||||
{
|
||||
_store.Add([Watched(_alice, _today, 10)]);
|
||||
Assert.True(File.Exists(_temp.FilePath));
|
||||
|
||||
// A second instance on the same file, as after a server restart.
|
||||
var reopened = new SqliteWatchStatsStore(_temp.Open());
|
||||
|
||||
Assert.Single(reopened.GetSince(_today));
|
||||
Assert.Equal(HeraldDatabase.SchemaVersion, _temp.Database.Read(connection =>
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA user_version;";
|
||||
return Convert.ToInt32(command.ExecuteScalar(), System.Globalization.CultureInfo.InvariantCulture);
|
||||
}));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Add_FromManyThreadsLosesNothing()
|
||||
{
|
||||
var tasks = Enumerable.Range(0, 8).Select(_ => Task.Run(() =>
|
||||
{
|
||||
for (var i = 0; i < 50; i++)
|
||||
{
|
||||
_store.Add([Watched(_alice, _today, 1, plays: 1)]);
|
||||
}
|
||||
}));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
var row = Assert.Single(_store.GetSince(_today));
|
||||
Assert.Equal(400, row.WatchedSeconds, 6);
|
||||
Assert.Equal(400, row.PlayCount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Jellyfin.Plugin.Herald.Storage;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// A database in a throwaway directory.
|
||||
/// </summary>
|
||||
public sealed class TempDatabase : IDisposable
|
||||
{
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), "herald-tests-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public TempDatabase()
|
||||
{
|
||||
Database = Open();
|
||||
}
|
||||
|
||||
public HeraldDatabase Database { get; }
|
||||
|
||||
public string FilePath => Path.Combine(_directory, "nested", "herald.db");
|
||||
|
||||
public HeraldDatabase Open() => new(FilePath, NullLogger<HeraldDatabase>.Instance);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
if (Directory.Exists(_directory))
|
||||
{
|
||||
Directory.Delete(_directory, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
using Jellyfin.Plugin.Herald.Stats;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Tests;
|
||||
|
||||
public class WatchTimeTrackerTests
|
||||
{
|
||||
private const string Key = "session|item";
|
||||
private static readonly Guid _alice = Guid.NewGuid();
|
||||
private static readonly Guid _bob = Guid.NewGuid();
|
||||
private static readonly Guid[] _users = [_alice];
|
||||
private static readonly DateTimeOffset _noon = new(2026, 3, 10, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly WatchTimeTracker _tracker = new(TimeZoneInfo.Utc);
|
||||
|
||||
private static double Seconds(IEnumerable<WatchIncrement> increments) => increments.Sum(i => i.Seconds);
|
||||
|
||||
private static DateTimeOffset At(double seconds) => _noon.AddSeconds(seconds);
|
||||
|
||||
[Fact]
|
||||
public void Start_CountsOnePlayPerUserAndNoTime()
|
||||
{
|
||||
var increments = _tracker.Start(Key, [_alice, _bob], _noon);
|
||||
|
||||
Assert.Equal(2, increments.Count);
|
||||
Assert.All(increments, i =>
|
||||
{
|
||||
Assert.Equal(1, i.Plays);
|
||||
Assert.Equal(0, i.Seconds);
|
||||
Assert.Equal(new DateOnly(2026, 3, 10), i.Date);
|
||||
Assert.Equal(_noon.UtcDateTime, i.Activity);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Progress_AddsTimeBetweenReports()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
var total = Seconds(_tracker.Progress(Key, _users, false, At(10)))
|
||||
+ Seconds(_tracker.Progress(Key, _users, false, At(20)))
|
||||
+ Seconds(_tracker.Stop(Key, _users, At(25)));
|
||||
|
||||
Assert.Equal(25, total);
|
||||
Assert.Equal(0, _tracker.ActiveCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Progress_NeverAddsPlays()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
var increments = _tracker.Progress(Key, _users, false, At(10));
|
||||
|
||||
Assert.All(increments, i => Assert.Equal(0, i.Plays));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pause_TimeWhilePausedIsNotCounted()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
// 10 s playing, then the client reports the pause.
|
||||
var beforePause = Seconds(_tracker.Progress(Key, _users, true, At(10)));
|
||||
// Paused clients keep reporting.
|
||||
var paused = Seconds(_tracker.Progress(Key, _users, true, At(20)))
|
||||
+ Seconds(_tracker.Progress(Key, _users, true, At(50)));
|
||||
// Unpause report, then 10 s of playback.
|
||||
var unpause = Seconds(_tracker.Progress(Key, _users, false, At(55)));
|
||||
var afterPause = Seconds(_tracker.Progress(Key, _users, false, At(65)));
|
||||
|
||||
Assert.Equal(10, beforePause);
|
||||
Assert.Equal(0, paused);
|
||||
Assert.Equal(0, unpause);
|
||||
Assert.Equal(10, afterPause);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Stop_WhilePausedAddsNothing()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
_tracker.Progress(Key, _users, true, At(10));
|
||||
|
||||
Assert.Empty(_tracker.Stop(Key, _users, At(40)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Seek_ExtraReportsDoNotAddMoreThanElapsedTime()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
// Seeking an hour ahead makes clients send reports in quick succession.
|
||||
// Only the clock matters, so the jump in position is worth nothing.
|
||||
var total = Seconds(_tracker.Progress(Key, _users, false, At(10)))
|
||||
+ Seconds(_tracker.Progress(Key, _users, false, At(10.2)))
|
||||
+ Seconds(_tracker.Progress(Key, _users, false, At(10.4)))
|
||||
+ Seconds(_tracker.Progress(Key, _users, false, At(20)));
|
||||
|
||||
Assert.Equal(20, total, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gap_IsCappedAtMaxDelta()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
var seconds = Seconds(_tracker.Progress(Key, _users, false, At(200)));
|
||||
|
||||
Assert.Equal(WatchTimeTracker.MaxDelta.TotalSeconds, seconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gap_LongerThanStaleLimitAddsNothingAndResumes()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
var afterGap = Seconds(_tracker.Progress(Key, _users, false, At(301)));
|
||||
var next = Seconds(_tracker.Progress(Key, _users, false, At(311)));
|
||||
|
||||
Assert.Equal(0, afterGap);
|
||||
Assert.Equal(10, next);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClockGoingBackwards_AddsNothing()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
|
||||
Assert.Empty(_tracker.Progress(Key, _users, false, At(-30)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CloseStale_RemovesOnlySilentPlaybacks()
|
||||
{
|
||||
_tracker.Start("quiet", _users, _noon);
|
||||
_tracker.Start("alive", _users, _noon);
|
||||
_tracker.Progress("alive", _users, false, At(280));
|
||||
|
||||
var closed = _tracker.CloseStale(At(301));
|
||||
|
||||
Assert.Equal(1, closed);
|
||||
Assert.Equal(1, _tracker.ActiveCount);
|
||||
Assert.Equal(10, Seconds(_tracker.Progress("alive", _users, false, At(290))));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StaleSession_StopAfterSweepAddsNothing()
|
||||
{
|
||||
_tracker.Start(Key, _users, _noon);
|
||||
_tracker.CloseStale(At(400));
|
||||
|
||||
Assert.Empty(_tracker.Stop(Key, _users, At(410)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Progress_ForUnknownPlaybackStartsTrackingWithoutTime()
|
||||
{
|
||||
var first = _tracker.Progress(Key, _users, false, _noon);
|
||||
var second = Seconds(_tracker.Progress(Key, _users, false, At(10)));
|
||||
|
||||
Assert.Empty(first);
|
||||
Assert.Equal(10, second);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Midnight_DeltaIsSplitBetweenBothDays()
|
||||
{
|
||||
var beforeMidnight = new DateTimeOffset(2026, 3, 10, 23, 59, 50, TimeSpan.Zero);
|
||||
_tracker.Start(Key, _users, beforeMidnight);
|
||||
|
||||
var increments = _tracker.Progress(Key, _users, false, beforeMidnight.AddSeconds(30));
|
||||
|
||||
Assert.Equal(2, increments.Count);
|
||||
var yesterday = Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 10));
|
||||
var today = Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 11));
|
||||
Assert.Equal(10, yesterday.Seconds, 6);
|
||||
Assert.Equal(20, today.Seconds, 6);
|
||||
Assert.Equal(new DateTime(2026, 3, 11, 0, 0, 0, DateTimeKind.Utc), yesterday.Activity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Midnight_FollowsTheServerTimeZone()
|
||||
{
|
||||
var zone = TimeZoneInfo.CreateCustomTimeZone("test+2", TimeSpan.FromHours(2), "test+2", "test+2");
|
||||
var tracker = new WatchTimeTracker(zone);
|
||||
|
||||
// 21:59:50 UTC is 23:59:50 local.
|
||||
var start = new DateTimeOffset(2026, 3, 10, 21, 59, 50, TimeSpan.Zero);
|
||||
var started = tracker.Start(Key, _users, start);
|
||||
var increments = tracker.Progress(Key, _users, false, start.AddSeconds(30));
|
||||
|
||||
Assert.Equal(new DateOnly(2026, 3, 10), Assert.Single(started).Date);
|
||||
Assert.Equal(10, Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 10)).Seconds, 6);
|
||||
Assert.Equal(20, Assert.Single(increments, i => i.Date == new DateOnly(2026, 3, 11)).Seconds, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Midnight_CappedGapOnlyCountsTheLastMinute()
|
||||
{
|
||||
var beforeMidnight = new DateTimeOffset(2026, 3, 10, 23, 57, 0, TimeSpan.Zero);
|
||||
_tracker.Start(Key, _users, beforeMidnight);
|
||||
|
||||
// 4 minutes without a report, ending 60 s after midnight: all counted time is on the new day.
|
||||
var increments = _tracker.Progress(Key, _users, false, beforeMidnight.AddMinutes(4));
|
||||
|
||||
var only = Assert.Single(increments);
|
||||
Assert.Equal(new DateOnly(2026, 3, 11), only.Date);
|
||||
Assert.Equal(60, only.Seconds, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SeparatePlaybacks_AreTrackedIndependently()
|
||||
{
|
||||
_tracker.Start("a", [_alice], _noon);
|
||||
_tracker.Start("b", [_bob], At(5));
|
||||
|
||||
var a = _tracker.Progress("a", [_alice], false, At(10));
|
||||
var b = _tracker.Progress("b", [_bob], false, At(10));
|
||||
|
||||
Assert.Equal(10, Assert.Single(a).Seconds);
|
||||
Assert.Equal(_alice, a[0].UserId);
|
||||
Assert.Equal(5, Assert.Single(b).Seconds);
|
||||
Assert.Equal(_bob, b[0].UserId);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
<Solution>
|
||||
<Project Path="Jellyfin.Plugin.Herald/Jellyfin.Plugin.Herald.csproj" />
|
||||
<Project Path="Jellyfin.Plugin.Herald.Tests/Jellyfin.Plugin.Herald.Tests.csproj" />
|
||||
</Solution>
|
||||
|
||||
@@ -83,6 +83,7 @@ public class HeraldController : ControllerBase
|
||||
Title = n.Title,
|
||||
Body = n.Body,
|
||||
RequireAccept = n.RequireAccept,
|
||||
AcceptDelaySeconds = n.AcceptDelaySeconds,
|
||||
Revision = n.Revision
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ public class PendingNotice
|
||||
/// </summary>
|
||||
public bool RequireAccept { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of seconds the notice has to be on screen before it can be accepted.
|
||||
/// </summary>
|
||||
public int AcceptDelaySeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the revision to send back with the response.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Herald</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="HeraldConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox,emby-textarea">
|
||||
<style>
|
||||
#HeraldConfigPage .heraldTabs { display: flex; margin: 0 0 1.5em; border-bottom: 1px solid rgba(128, 128, 128, .35); }
|
||||
#HeraldConfigPage .heraldTab { padding: .9em 1.4em; margin: 0 0 -1px; border: 0; border-bottom: .2em solid transparent; background: none; font: inherit; font-weight: 600; cursor: pointer; }
|
||||
#HeraldConfigPage .heraldTab.emby-tab-button-active { border-bottom-color: #00a4dc !important; }
|
||||
#HeraldConfigPage .heraldBar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5em 1em; margin-bottom: 1em; }
|
||||
#HeraldConfigPage .heraldBar h2 { margin: 0; }
|
||||
#HeraldConfigPage .heraldBar button { margin: 0; }
|
||||
#HeraldConfigPage .heraldEmpty { padding: 1.5em 0; opacity: .75; }
|
||||
#HeraldConfigPage .heraldOff { opacity: .55; }
|
||||
#HeraldConfigPage .heraldRowActions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; flex-shrink: 0; }
|
||||
#HeraldConfigPage .heraldRowActions .checkboxContainer { margin: 0 .6em 0 0; }
|
||||
#HeraldConfigPage .heraldPanel { margin: 1.5em 0 0; }
|
||||
#HeraldConfigPage .heraldPanel h3 { margin: 1.4em 0 .5em; }
|
||||
#HeraldConfigPage .heraldUsers { max-height: 20em; overflow-y: auto; padding: .4em 1em; margin-bottom: 1.8em; }
|
||||
#HeraldConfigPage .heraldUsers .emby-checkbox-label { display: flex; margin: .5em 0; }
|
||||
#HeraldConfigPage .heraldFormButtons { display: flex; flex-wrap: wrap; gap: .5em 1em; }
|
||||
#HeraldConfigPage .heraldFormButtons button { flex: 1 1 12em; margin: 0; justify-content: center; }
|
||||
#HeraldConfigPage #heraldBody { font-family: inherit; line-height: 1.5; padding: .6em; box-sizing: border-box; }
|
||||
#HeraldConfigPage .heraldTableWrap { overflow-x: auto; }
|
||||
#HeraldConfigPage .heraldTable th, #HeraldConfigPage .heraldTable td { padding: .65em .8em; white-space: nowrap; }
|
||||
#HeraldConfigPage .heraldTable tbody tr { border-top: 1px solid rgba(128, 128, 128, .25); }
|
||||
#HeraldConfigPage .heraldTable .heraldNum { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
#HeraldConfigPage .heraldSort { padding: 0; border: 0; background: none; color: inherit; font: inherit; font-weight: 700; cursor: pointer; }
|
||||
#HeraldConfigPage .heraldSort[data-dir="asc"]::after { content: " \25B4"; }
|
||||
#HeraldConfigPage .heraldSort[data-dir="desc"]::after { content: " \25BE"; }
|
||||
#HeraldConfigPage .heraldShare { display: block; height: .18em; margin-top: .3em; margin-left: auto; background: currentColor; opacity: .45; }
|
||||
#HeraldConfigPage .heraldGone { font-style: italic; opacity: .7; }
|
||||
</style>
|
||||
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<div class="heraldTabs" role="tablist">
|
||||
<button type="button" class="heraldTab emby-tab-button emby-tab-button-active" role="tab" aria-selected="true" data-tab="notices">Notices</button>
|
||||
<button type="button" class="heraldTab emby-tab-button" role="tab" aria-selected="false" data-tab="stats">Stats</button>
|
||||
</div>
|
||||
|
||||
<div id="heraldNoticesTab" role="tabpanel">
|
||||
<div class="heraldBar">
|
||||
<h2 class="sectionTitle">Notices</h2>
|
||||
<button is="emby-button" type="button" id="heraldNewNotice" class="raised button-submit emby-button">
|
||||
<span>New notice</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="fieldDescription">Each notice pops up once per user in the web client. It does not show in native apps (Android TV, Swiftfin, Kodi and the like).</div>
|
||||
|
||||
<div id="heraldNoticeList" class="paperList" style="margin-top: 1em;"></div>
|
||||
<div id="heraldNoticeEmpty" class="heraldEmpty hide">No notices yet.</div>
|
||||
|
||||
<form id="heraldNoticeForm" class="heraldPanel hide">
|
||||
<h2 class="sectionTitle" id="heraldFormTitle">New notice</h2>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="heraldTitle">Title</label>
|
||||
<input id="heraldTitle" type="text" is="emby-input" maxlength="200" required />
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="textareaLabel" for="heraldBody">Message</label>
|
||||
<textarea id="heraldBody" is="emby-textarea" class="emby-textarea" rows="8" maxlength="20000" style="width: 100%;"></textarea>
|
||||
<div class="fieldDescription">Plain text. Line breaks are kept. Also understood: **bold**, *italic*, [link text](https://example.org), and lines starting with "- " or "1. " as lists. HTML is shown as text.</div>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="heraldRequireAccept" type="checkbox" is="emby-checkbox" />
|
||||
<span>Require users to accept</span>
|
||||
</label>
|
||||
<div class="fieldDescription checkboxFieldDescription">The notice can only be closed with an "Accept" button.</div>
|
||||
</div>
|
||||
<div class="inputContainer" id="heraldDelayField">
|
||||
<label class="inputLabel inputLabelUnfocused" for="heraldAcceptDelay">Wait before "Accept" can be clicked (seconds)</label>
|
||||
<input id="heraldAcceptDelay" type="number" is="emby-input" min="0" max="600" step="1" value="0" />
|
||||
<div class="fieldDescription">The button stays locked and counts down while the notice is on screen. 0 means no wait.</div>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="heraldEnabled" type="checkbox" is="emby-checkbox" checked />
|
||||
<span>Enabled</span>
|
||||
</label>
|
||||
<div class="fieldDescription checkboxFieldDescription">Disabled notices are kept but not shown to anyone.</div>
|
||||
</div>
|
||||
<div class="selectContainer">
|
||||
<label class="selectLabel" for="heraldTarget">Show to</label>
|
||||
<select is="emby-select" id="heraldTarget" class="emby-select-withcolor emby-select">
|
||||
<option value="all">All users</option>
|
||||
<option value="selected">Selected users</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="heraldUsers" class="heraldUsers paperList hide"></div>
|
||||
<div class="heraldFormButtons">
|
||||
<button is="emby-button" type="submit" class="raised button-submit emby-button">
|
||||
<span>Save</span>
|
||||
</button>
|
||||
<button is="emby-button" type="button" id="heraldCancel" class="raised button-cancel emby-button">
|
||||
<span>Cancel</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div id="heraldAcks" class="heraldPanel hide">
|
||||
<div class="heraldBar">
|
||||
<h2 class="sectionTitle" id="heraldAcksTitle">Responses</h2>
|
||||
<button is="emby-button" type="button" id="heraldAcksClose" class="raised button-cancel emby-button">
|
||||
<span>Close</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="fieldDescription" id="heraldAcksNote"></div>
|
||||
<h3>Responded</h3>
|
||||
<div class="heraldTableWrap">
|
||||
<table class="detailTable heraldTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="detailTableHeaderCell">User</th>
|
||||
<th class="detailTableHeaderCell">Response</th>
|
||||
<th class="detailTableHeaderCell">When</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="heraldAcksRows"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<h3>Not yet</h3>
|
||||
<div id="heraldAcksPending"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="heraldStatsTab" role="tabpanel" class="hide">
|
||||
<div class="heraldBar">
|
||||
<h2 class="sectionTitle">Watch time</h2>
|
||||
<button is="emby-button" type="button" id="heraldStatsRefresh" class="raised button-cancel emby-button">
|
||||
<span>Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="fieldDescription">Approximate time spent playing, counted from the progress reports clients send while playing. Paused time is left out. Days follow the server's clock.</div>
|
||||
<div class="heraldTableWrap" style="margin-top: 1em;">
|
||||
<table class="detailTable heraldTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="detailTableHeaderCell"><button type="button" class="heraldSort" data-sort="name">User</button></th>
|
||||
<th class="detailTableHeaderCell heraldNum"><button type="button" class="heraldSort" data-sort="week">Last 7 days</button></th>
|
||||
<th class="detailTableHeaderCell heraldNum"><button type="button" class="heraldSort" data-sort="month">Last 30 days</button></th>
|
||||
<th class="detailTableHeaderCell heraldNum"><button type="button" class="heraldSort" data-sort="plays">Plays (30 days)</button></th>
|
||||
<th class="detailTableHeaderCell"><button type="button" class="heraldSort" data-sort="last">Last active</button></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="heraldStatsRows"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="heraldStatsEmpty" class="heraldEmpty hide">No users.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var page = document.querySelector('#HeraldConfigPage');
|
||||
var byId = function (id) { return page.querySelector('#' + id); };
|
||||
|
||||
var notices = [];
|
||||
var users = [];
|
||||
var editingId = null;
|
||||
var acksFor = null;
|
||||
var stats = [];
|
||||
var statsLoaded = false;
|
||||
var sort = { key: 'month', dir: 'desc' };
|
||||
|
||||
// ------------------------------------------------------------ helpers
|
||||
|
||||
function api(method, path, body) {
|
||||
var options = { type: method, url: ApiClient.getUrl(path) };
|
||||
if (body) {
|
||||
options.data = JSON.stringify(body);
|
||||
options.contentType = 'application/json';
|
||||
}
|
||||
if (method === 'GET' || body) {
|
||||
options.dataType = 'json';
|
||||
}
|
||||
return ApiClient.ajax(options);
|
||||
}
|
||||
|
||||
function busy(promise) {
|
||||
Dashboard.showLoadingMsg();
|
||||
return promise.then(function (result) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
return result;
|
||||
}, function (response) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
describeError(response).then(function (message) {
|
||||
Dashboard.alert(message);
|
||||
});
|
||||
throw response;
|
||||
});
|
||||
}
|
||||
|
||||
function describeError(response) {
|
||||
var fallback = 'Something went wrong. Check the server log.';
|
||||
if (!response || typeof response.json !== 'function') {
|
||||
return Promise.resolve(fallback);
|
||||
}
|
||||
return response.json().then(function (problem) {
|
||||
return (problem && (problem.detail || problem.title)) || fallback;
|
||||
}, function () {
|
||||
return fallback;
|
||||
});
|
||||
}
|
||||
|
||||
function el(tag, className, text) {
|
||||
var node = document.createElement(tag);
|
||||
if (className) {
|
||||
node.className = className;
|
||||
}
|
||||
if (text !== undefined && text !== null) {
|
||||
node.textContent = text;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
function clear(node) {
|
||||
while (node.firstChild) {
|
||||
node.removeChild(node.firstChild);
|
||||
}
|
||||
}
|
||||
|
||||
function toggle(node, visible) {
|
||||
node.classList.toggle('hide', !visible);
|
||||
}
|
||||
|
||||
function when(value) {
|
||||
return value ? new Date(value).toLocaleString() : 'never';
|
||||
}
|
||||
|
||||
function duration(seconds) {
|
||||
if (!seconds || seconds <= 0) {
|
||||
return '–';
|
||||
}
|
||||
if (seconds < 60) {
|
||||
return '< 1 min';
|
||||
}
|
||||
var minutes = Math.round(seconds / 60);
|
||||
var h = Math.floor(minutes / 60);
|
||||
var m = minutes % 60;
|
||||
return h ? h + ' h ' + (m < 10 ? '0' : '') + m + ' min' : m + ' min';
|
||||
}
|
||||
|
||||
function userName(id) {
|
||||
for (var i = 0; i < users.length; i++) {
|
||||
if (users[i].Id.replace(/-/g, '') === String(id).replace(/-/g, '')) {
|
||||
return users[i].Name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Jellyfin's custom elements only upgrade when they come out of the HTML parser,
|
||||
// so the element shells are parsed from fixed markup. Anything variable is set as text afterwards.
|
||||
function parsed(markup) {
|
||||
var holder = document.createElement('div');
|
||||
holder.innerHTML = markup;
|
||||
return holder.firstChild;
|
||||
}
|
||||
|
||||
function checkbox(labelText, checked) {
|
||||
var label = parsed('<label class="emby-checkbox-label"><input type="checkbox" is="emby-checkbox" /><span></span></label>');
|
||||
var input = label.querySelector('input');
|
||||
input.checked = !!checked;
|
||||
label.querySelector('span').textContent = labelText;
|
||||
return { label: label, input: input };
|
||||
}
|
||||
|
||||
function iconButton(icon, title, onClick) {
|
||||
var button = parsed('<button type="button" is="paper-icon-button-light"><span class="material-icons" aria-hidden="true"></span></button>');
|
||||
button.title = title;
|
||||
button.setAttribute('aria-label', title);
|
||||
button.querySelector('span').classList.add(icon);
|
||||
button.addEventListener('click', onClick);
|
||||
return button;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ notices
|
||||
|
||||
function loadNotices() {
|
||||
return busy(api('GET', 'Herald/Notices')).then(function (result) {
|
||||
notices = result || [];
|
||||
renderNotices();
|
||||
});
|
||||
}
|
||||
|
||||
function describeTarget(notice) {
|
||||
if (notice.Target.AllUsers) {
|
||||
return 'All users';
|
||||
}
|
||||
var names = notice.Target.UserIds.map(function (id) { return userName(id) || 'deleted user'; });
|
||||
if (names.length <= 3) {
|
||||
return names.join(', ');
|
||||
}
|
||||
return names.slice(0, 3).join(', ') + ' and ' + (names.length - 3) + ' more';
|
||||
}
|
||||
|
||||
function renderNotices() {
|
||||
var list = byId('heraldNoticeList');
|
||||
clear(list);
|
||||
toggle(byId('heraldNoticeEmpty'), notices.length === 0);
|
||||
toggle(list, notices.length > 0);
|
||||
|
||||
notices.slice().reverse().forEach(function (notice) {
|
||||
var row = el('div', 'listItem listItem-border');
|
||||
|
||||
var text = el('div', 'listItemBody two-line' + (notice.Enabled ? '' : ' heraldOff'));
|
||||
text.appendChild(el('h3', 'listItemBodyText', notice.Title));
|
||||
var meta = [describeTarget(notice)];
|
||||
if (notice.RequireAccept) {
|
||||
meta.push(notice.AcceptDelaySeconds > 0 ? 'must be accepted after ' + notice.AcceptDelaySeconds + ' s' : 'must be accepted');
|
||||
}
|
||||
if (notice.Revision > 1) {
|
||||
meta.push('shown ' + notice.Revision + ' times');
|
||||
}
|
||||
meta.push('changed ' + when(notice.UpdatedAt));
|
||||
text.appendChild(el('div', 'listItemBodyText secondary', meta.join(' · ')));
|
||||
row.appendChild(text);
|
||||
|
||||
var actions = el('div', 'heraldRowActions');
|
||||
var enabled = checkbox('Enabled', notice.Enabled);
|
||||
var holder = el('div', 'checkboxContainer');
|
||||
holder.appendChild(enabled.label);
|
||||
enabled.input.addEventListener('change', function () {
|
||||
setEnabled(notice, enabled.input.checked);
|
||||
});
|
||||
actions.appendChild(holder);
|
||||
actions.appendChild(iconButton('people', 'Responses', function () { showAcks(notice.Id); }));
|
||||
actions.appendChild(iconButton('replay', 'Re-show to everyone', function () { reshow(notice); }));
|
||||
actions.appendChild(iconButton('edit', 'Edit', function () { openForm(notice); }));
|
||||
actions.appendChild(iconButton('delete', 'Delete', function () { remove(notice); }));
|
||||
row.appendChild(actions);
|
||||
|
||||
list.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
function draftOf(notice) {
|
||||
return {
|
||||
Title: notice.Title,
|
||||
Body: notice.Body,
|
||||
RequireAccept: notice.RequireAccept,
|
||||
AcceptDelaySeconds: notice.AcceptDelaySeconds || 0,
|
||||
Enabled: notice.Enabled,
|
||||
Target: { AllUsers: notice.Target.AllUsers, UserIds: notice.Target.UserIds }
|
||||
};
|
||||
}
|
||||
|
||||
function setEnabled(notice, enabled) {
|
||||
var draft = draftOf(notice);
|
||||
draft.Enabled = enabled;
|
||||
busy(api('PUT', 'Herald/Notices/' + notice.Id, draft)).then(loadNotices, loadNotices);
|
||||
}
|
||||
|
||||
function ask(message, title, onYes) {
|
||||
if (typeof Dashboard.confirm === 'function') {
|
||||
Dashboard.confirm(message, title, function (yes) {
|
||||
if (yes) {
|
||||
onYes();
|
||||
}
|
||||
});
|
||||
} else if (window.confirm(message)) {
|
||||
onYes();
|
||||
}
|
||||
}
|
||||
|
||||
function reshow(notice) {
|
||||
ask('Show "' + notice.Title + '" again to everyone it is addressed to, including users who already responded?', 'Re-show to everyone', function () {
|
||||
busy(api('POST', 'Herald/Notices/' + notice.Id + '/Reshow')).then(function () {
|
||||
return loadNotices();
|
||||
}).then(function () {
|
||||
if (acksFor === notice.Id) {
|
||||
showAcks(notice.Id);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function remove(notice) {
|
||||
ask('Delete "' + notice.Title + '" and its recorded responses?', 'Delete notice', function () {
|
||||
busy(api('DELETE', 'Herald/Notices/' + notice.Id)).then(function () {
|
||||
if (editingId === notice.Id) {
|
||||
closeForm();
|
||||
}
|
||||
if (acksFor === notice.Id) {
|
||||
closeAcks();
|
||||
}
|
||||
return loadNotices();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ form
|
||||
|
||||
function renderUserPicker(selectedIds) {
|
||||
var box = byId('heraldUsers');
|
||||
clear(box);
|
||||
var selected = {};
|
||||
(selectedIds || []).forEach(function (id) { selected[String(id).replace(/-/g, '')] = true; });
|
||||
|
||||
users.forEach(function (user) {
|
||||
var item = checkbox(user.Name, selected[user.Id.replace(/-/g, '')]);
|
||||
item.input.setAttribute('data-user-id', user.Id);
|
||||
box.appendChild(item.label);
|
||||
});
|
||||
}
|
||||
|
||||
function openForm(notice) {
|
||||
closeAcks();
|
||||
editingId = notice ? notice.Id : null;
|
||||
byId('heraldFormTitle').textContent = notice ? 'Edit notice' : 'New notice';
|
||||
byId('heraldTitle').value = notice ? notice.Title : '';
|
||||
byId('heraldBody').value = notice ? notice.Body : '';
|
||||
byId('heraldRequireAccept').checked = notice ? notice.RequireAccept : false;
|
||||
byId('heraldAcceptDelay').value = notice ? (notice.AcceptDelaySeconds || 0) : 0;
|
||||
toggle(byId('heraldDelayField'), byId('heraldRequireAccept').checked);
|
||||
byId('heraldEnabled').checked = notice ? notice.Enabled : true;
|
||||
byId('heraldTarget').value = notice && !notice.Target.AllUsers ? 'selected' : 'all';
|
||||
renderUserPicker(notice ? notice.Target.UserIds : []);
|
||||
toggle(byId('heraldUsers'), byId('heraldTarget').value === 'selected');
|
||||
toggle(byId('heraldNoticeForm'), true);
|
||||
byId('heraldTitle').focus();
|
||||
}
|
||||
|
||||
function closeForm() {
|
||||
editingId = null;
|
||||
toggle(byId('heraldNoticeForm'), false);
|
||||
}
|
||||
|
||||
function submitForm(e) {
|
||||
e.preventDefault();
|
||||
|
||||
var allUsers = byId('heraldTarget').value !== 'selected';
|
||||
var userIds = [];
|
||||
if (!allUsers) {
|
||||
var boxes = byId('heraldUsers').querySelectorAll('input[data-user-id]');
|
||||
for (var i = 0; i < boxes.length; i++) {
|
||||
if (boxes[i].checked) {
|
||||
userIds.push(boxes[i].getAttribute('data-user-id'));
|
||||
}
|
||||
}
|
||||
if (!userIds.length) {
|
||||
Dashboard.alert('Select at least one user, or show the notice to all users.');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var draft = {
|
||||
Title: byId('heraldTitle').value,
|
||||
Body: byId('heraldBody').value,
|
||||
RequireAccept: byId('heraldRequireAccept').checked,
|
||||
AcceptDelaySeconds: byId('heraldRequireAccept').checked ? (parseInt(byId('heraldAcceptDelay').value, 10) || 0) : 0,
|
||||
Enabled: byId('heraldEnabled').checked,
|
||||
Target: { AllUsers: allUsers, UserIds: userIds }
|
||||
};
|
||||
|
||||
var request = editingId
|
||||
? api('PUT', 'Herald/Notices/' + editingId, draft)
|
||||
: api('POST', 'Herald/Notices', draft);
|
||||
|
||||
busy(request).then(function () {
|
||||
closeForm();
|
||||
return loadNotices();
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ responses
|
||||
|
||||
function showAcks(noticeId) {
|
||||
closeForm();
|
||||
busy(api('GET', 'Herald/Notices/' + noticeId + '/Acks')).then(function (report) {
|
||||
acksFor = noticeId;
|
||||
var notice = notices.filter(function (n) { return n.Id === noticeId; })[0];
|
||||
byId('heraldAcksTitle').textContent = 'Responses: ' + (notice ? notice.Title : '');
|
||||
byId('heraldAcksNote').textContent = report.Revision > 1
|
||||
? 'Since it was last re-shown (round ' + report.Revision + ').'
|
||||
: '';
|
||||
|
||||
var rows = byId('heraldAcksRows');
|
||||
clear(rows);
|
||||
if (!report.Responses.length) {
|
||||
var none = el('tr');
|
||||
var cell = el('td', 'detailTableBodyCell', 'Nobody has responded yet.');
|
||||
cell.colSpan = 3;
|
||||
none.appendChild(cell);
|
||||
rows.appendChild(none);
|
||||
}
|
||||
report.Responses.forEach(function (entry) {
|
||||
var row = el('tr');
|
||||
row.appendChild(el('td', 'detailTableBodyCell' + (entry.UserName ? '' : ' heraldGone'), entry.UserName || 'deleted user'));
|
||||
row.appendChild(el('td', 'detailTableBodyCell', entry.Action));
|
||||
row.appendChild(el('td', 'detailTableBodyCell', when(entry.Timestamp)));
|
||||
rows.appendChild(row);
|
||||
});
|
||||
|
||||
var pending = byId('heraldAcksPending');
|
||||
pending.textContent = report.Pending.length
|
||||
? report.Pending.map(function (entry) { return entry.UserName; }).join(', ')
|
||||
: 'Everyone it is addressed to has responded.';
|
||||
|
||||
toggle(byId('heraldAcks'), true);
|
||||
byId('heraldAcks').scrollIntoView({ block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
function closeAcks() {
|
||||
acksFor = null;
|
||||
toggle(byId('heraldAcks'), false);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ stats
|
||||
|
||||
function loadStats() {
|
||||
return busy(Promise.all([api('GET', 'Herald/Stats?days=7'), api('GET', 'Herald/Stats?days=30')])).then(function (results) {
|
||||
var week = {};
|
||||
(results[0] || []).forEach(function (entry) { week[entry.UserId] = entry; });
|
||||
stats = (results[1] || []).map(function (entry) {
|
||||
return {
|
||||
name: entry.UserName || null,
|
||||
week: week[entry.UserId] ? week[entry.UserId].WatchedSeconds : 0,
|
||||
month: entry.WatchedSeconds || 0,
|
||||
plays: entry.PlayCount || 0,
|
||||
last: entry.LastActivity ? new Date(entry.LastActivity).getTime() : 0
|
||||
};
|
||||
});
|
||||
statsLoaded = true;
|
||||
renderStats();
|
||||
});
|
||||
}
|
||||
|
||||
function renderStats() {
|
||||
var direction = sort.dir === 'asc' ? 1 : -1;
|
||||
var sorted = stats.slice().sort(function (a, b) {
|
||||
var result = sort.key === 'name'
|
||||
? (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' })
|
||||
: a[sort.key] - b[sort.key];
|
||||
return result * direction || (a.name || '').localeCompare(b.name || '');
|
||||
});
|
||||
|
||||
var top = stats.reduce(function (max, entry) { return Math.max(max, entry.month); }, 0);
|
||||
var rows = byId('heraldStatsRows');
|
||||
clear(rows);
|
||||
toggle(byId('heraldStatsEmpty'), sorted.length === 0);
|
||||
|
||||
sorted.forEach(function (entry) {
|
||||
var row = el('tr');
|
||||
row.appendChild(el('td', 'detailTableBodyCell' + (entry.name ? '' : ' heraldGone'), entry.name || 'deleted user'));
|
||||
row.appendChild(el('td', 'detailTableBodyCell heraldNum', duration(entry.week)));
|
||||
|
||||
var month = el('td', 'detailTableBodyCell heraldNum', duration(entry.month));
|
||||
if (top > 0 && entry.month > 0) {
|
||||
// Share of the busiest user's time, as a hairline under the value.
|
||||
var share = el('span', 'heraldShare');
|
||||
share.style.width = Math.max(4, Math.round(entry.month / top * 100)) + '%';
|
||||
month.appendChild(share);
|
||||
}
|
||||
row.appendChild(month);
|
||||
|
||||
row.appendChild(el('td', 'detailTableBodyCell heraldNum', entry.plays ? String(entry.plays) : '–'));
|
||||
row.appendChild(el('td', 'detailTableBodyCell', entry.last ? new Date(entry.last).toLocaleString() : 'not in the last 30 days'));
|
||||
rows.appendChild(row);
|
||||
});
|
||||
|
||||
var headers = page.querySelectorAll('.heraldSort');
|
||||
for (var i = 0; i < headers.length; i++) {
|
||||
var active = headers[i].getAttribute('data-sort') === sort.key;
|
||||
if (active) {
|
||||
headers[i].setAttribute('data-dir', sort.dir);
|
||||
} else {
|
||||
headers[i].removeAttribute('data-dir');
|
||||
}
|
||||
headers[i].parentNode.setAttribute('aria-sort', active ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none');
|
||||
}
|
||||
}
|
||||
|
||||
function sortBy(key) {
|
||||
if (sort.key === key) {
|
||||
sort.dir = sort.dir === 'asc' ? 'desc' : 'asc';
|
||||
} else {
|
||||
sort.key = key;
|
||||
sort.dir = key === 'name' ? 'asc' : 'desc';
|
||||
}
|
||||
renderStats();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ tabs and wiring
|
||||
|
||||
function showTab(name) {
|
||||
var tabs = page.querySelectorAll('.heraldTab');
|
||||
for (var i = 0; i < tabs.length; i++) {
|
||||
var active = tabs[i].getAttribute('data-tab') === name;
|
||||
tabs[i].classList.toggle('emby-tab-button-active', active);
|
||||
tabs[i].setAttribute('aria-selected', active ? 'true' : 'false');
|
||||
}
|
||||
toggle(byId('heraldNoticesTab'), name === 'notices');
|
||||
toggle(byId('heraldStatsTab'), name === 'stats');
|
||||
if (name === 'stats' && !statsLoaded) {
|
||||
loadStats();
|
||||
}
|
||||
}
|
||||
|
||||
page.querySelector('.heraldTabs').addEventListener('click', function (e) {
|
||||
var tab = e.target.closest('.heraldTab');
|
||||
if (tab) {
|
||||
showTab(tab.getAttribute('data-tab'));
|
||||
}
|
||||
});
|
||||
|
||||
page.querySelector('#heraldStatsTab thead').addEventListener('click', function (e) {
|
||||
var header = e.target.closest('.heraldSort');
|
||||
if (header) {
|
||||
sortBy(header.getAttribute('data-sort'));
|
||||
}
|
||||
});
|
||||
|
||||
byId('heraldNewNotice').addEventListener('click', function () { openForm(null); });
|
||||
byId('heraldCancel').addEventListener('click', closeForm);
|
||||
byId('heraldAcksClose').addEventListener('click', closeAcks);
|
||||
byId('heraldStatsRefresh').addEventListener('click', loadStats);
|
||||
byId('heraldNoticeForm').addEventListener('submit', submitForm);
|
||||
byId('heraldRequireAccept').addEventListener('change', function () {
|
||||
toggle(byId('heraldDelayField'), this.checked);
|
||||
});
|
||||
byId('heraldTarget').addEventListener('change', function () {
|
||||
toggle(byId('heraldUsers'), byId('heraldTarget').value === 'selected');
|
||||
});
|
||||
|
||||
page.addEventListener('pageshow', function () {
|
||||
statsLoaded = false;
|
||||
showTab('notices');
|
||||
closeForm();
|
||||
closeAcks();
|
||||
busy(ApiClient.getUsers()).then(function (result) {
|
||||
users = (result || []).slice().sort(function (a, b) {
|
||||
return a.Name.localeCompare(b.Name, undefined, { sensitivity: 'base' });
|
||||
});
|
||||
return loadNotices();
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -17,9 +17,11 @@ namespace Jellyfin.Plugin.Herald.Injection;
|
||||
public class FileTransformationRegistrar : IHostedService
|
||||
{
|
||||
private const string InterfaceTypeName = "Jellyfin.Plugin.FileTransformation.PluginInterface";
|
||||
// File Transformation treats this as a regular expression. Unanchored, "index.html" would also
|
||||
// match script chunks such as "session-login-index-html.<hash>.chunk.js".
|
||||
private const string IndexHtmlPattern = @"^index\.html$";
|
||||
// Has to be the literal "index.html" every other plugin registers. File Transformation groups
|
||||
// callbacks by pattern string and, for a request, only runs the group whose key equals the path;
|
||||
// a differently spelled pattern is skipped as soon as another plugin uses the plain one.
|
||||
// The pattern is also used as a regex and matches some script chunks, which the transformer ignores.
|
||||
private const string IndexHtmlPattern = "index.html";
|
||||
private static readonly Guid _transformationId = Guid.Parse("bf6fabc9-721c-46d9-9e13-3cc415a9ae1b");
|
||||
|
||||
private readonly ILogger<FileTransformationRegistrar> _logger;
|
||||
|
||||
@@ -37,7 +37,7 @@ public static class IndexHtmlTransformer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts the script tag before the closing body tag. Content without one is not a page and is left alone.
|
||||
/// Inserts the script tag before the closing body tag. Anything that is not an HTML page is left alone.
|
||||
/// </summary>
|
||||
/// <param name="html">The page.</param>
|
||||
/// <returns>The page with the script tag.</returns>
|
||||
@@ -50,6 +50,12 @@ public static class IndexHtmlTransformer
|
||||
return html;
|
||||
}
|
||||
|
||||
// File Transformation also hands over script chunks whose name happens to match the pattern.
|
||||
if (!html.Contains("<html", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return html;
|
||||
}
|
||||
|
||||
var index = html.LastIndexOf("</body>", StringComparison.OrdinalIgnoreCase);
|
||||
return index < 0 ? html : html.Insert(index, ScriptTag);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ public class Notice
|
||||
/// </summary>
|
||||
public bool RequireAccept { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of seconds the notice has to be on screen before it can be accepted.
|
||||
/// </summary>
|
||||
public int AcceptDelaySeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the notice is shown at all.
|
||||
/// </summary>
|
||||
|
||||
@@ -20,6 +20,11 @@ public class NoticeDraft
|
||||
/// </summary>
|
||||
public bool RequireAccept { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of seconds the notice has to be on screen before it can be accepted.
|
||||
/// </summary>
|
||||
public int AcceptDelaySeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the notice is shown.
|
||||
/// </summary>
|
||||
|
||||
@@ -19,6 +19,11 @@ public static class NoticeRules
|
||||
/// </summary>
|
||||
public const int MaxBodyLength = 20000;
|
||||
|
||||
/// <summary>
|
||||
/// Longest wait before a notice can be accepted, in seconds.
|
||||
/// </summary>
|
||||
public const int MaxAcceptDelaySeconds = 600;
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether a notice is addressed to a user.
|
||||
/// </summary>
|
||||
@@ -124,6 +129,11 @@ public static class NoticeRules
|
||||
return "Body is too long.";
|
||||
}
|
||||
|
||||
if (draft.AcceptDelaySeconds < 0 || draft.AcceptDelaySeconds > MaxAcceptDelaySeconds)
|
||||
{
|
||||
return "The wait before accepting has to be between 0 and 600 seconds.";
|
||||
}
|
||||
|
||||
if (draft.Target is { AllUsers: false } target && (target.UserIds is null || target.UserIds.Count == 0))
|
||||
{
|
||||
return "Select at least one user or address all users.";
|
||||
|
||||
@@ -210,6 +210,7 @@ public class NoticeService
|
||||
notice.Title = (draft.Title ?? string.Empty).Trim();
|
||||
notice.Body = (draft.Body ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Trim();
|
||||
notice.RequireAccept = draft.RequireAccept;
|
||||
notice.AcceptDelaySeconds = draft.RequireAccept ? draft.AcceptDelaySeconds : 0;
|
||||
notice.Enabled = draft.Enabled;
|
||||
|
||||
var allUsers = draft.Target?.AllUsers ?? true;
|
||||
|
||||
@@ -47,6 +47,9 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = Name,
|
||||
DisplayName = Name,
|
||||
EnableInMainMenu = true,
|
||||
MenuIcon = "campaign",
|
||||
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Configuration.configPage.html", GetType().Namespace)
|
||||
}
|
||||
];
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using Jellyfin.Plugin.Herald.Injection;
|
||||
using Jellyfin.Plugin.Herald.Notices;
|
||||
using Jellyfin.Plugin.Herald.Stats;
|
||||
using Jellyfin.Plugin.Herald.Storage;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the plugin's services with the server.
|
||||
/// </summary>
|
||||
public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
|
||||
{
|
||||
serviceCollection.TryAddSingleton(TimeProvider.System);
|
||||
|
||||
serviceCollection.AddSingleton(provider => new HeraldDatabase(
|
||||
Path.Combine(provider.GetRequiredService<IApplicationPaths>().DataPath, "herald", "herald.db"),
|
||||
provider.GetRequiredService<ILogger<HeraldDatabase>>()));
|
||||
serviceCollection.AddSingleton<INoticeStore, SqliteNoticeStore>();
|
||||
serviceCollection.AddSingleton<IWatchStatsStore, SqliteWatchStatsStore>();
|
||||
|
||||
serviceCollection.AddSingleton<NoticeService>();
|
||||
serviceCollection.AddSingleton<StatsService>();
|
||||
serviceCollection.AddSingleton(provider => new WatchTimeTracker(provider.GetRequiredService<TimeProvider>().LocalTimeZone));
|
||||
|
||||
serviceCollection.AddHostedService<PlaybackTrackingService>();
|
||||
serviceCollection.AddHostedService<FileTransformationRegistrar>();
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,11 @@ public class HeraldDatabase
|
||||
PRIMARY KEY (user_id, date)
|
||||
);
|
||||
CREATE INDEX ix_watch_daily_date ON watch_daily (date);
|
||||
""",
|
||||
|
||||
// 3: wait before a notice can be accepted
|
||||
"""
|
||||
ALTER TABLE notices ADD COLUMN accept_delay INTEGER NOT NULL DEFAULT 0;
|
||||
"""
|
||||
];
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace Jellyfin.Plugin.Herald.Storage;
|
||||
/// </summary>
|
||||
public class SqliteNoticeStore : INoticeStore
|
||||
{
|
||||
private const string NoticeColumns = "id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at";
|
||||
private const string NoticeColumns = "id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at, accept_delay";
|
||||
private const string AckColumns = "notice_id, revision, user_id, action, timestamp";
|
||||
|
||||
private readonly HeraldDatabase _database;
|
||||
@@ -66,12 +66,13 @@ public class SqliteNoticeStore : INoticeStore
|
||||
connection,
|
||||
transaction,
|
||||
"""
|
||||
INSERT INTO notices (id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at)
|
||||
VALUES ($id, $title, $body, $requireAccept, $enabled, $targetAll, $targetUsers, $revision, $createdAt, $updatedAt)
|
||||
INSERT INTO notices (id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at, accept_delay)
|
||||
VALUES ($id, $title, $body, $requireAccept, $enabled, $targetAll, $targetUsers, $revision, $createdAt, $updatedAt, $acceptDelay)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
title = excluded.title,
|
||||
body = excluded.body,
|
||||
require_accept = excluded.require_accept,
|
||||
accept_delay = excluded.accept_delay,
|
||||
enabled = excluded.enabled,
|
||||
target_all = excluded.target_all,
|
||||
target_users = excluded.target_users,
|
||||
@@ -88,6 +89,7 @@ public class SqliteNoticeStore : INoticeStore
|
||||
command.Parameters.AddWithValue("$revision", notice.Revision);
|
||||
command.Parameters.AddWithValue("$createdAt", Db.Time(notice.CreatedAt));
|
||||
command.Parameters.AddWithValue("$updatedAt", Db.Time(notice.UpdatedAt));
|
||||
command.Parameters.AddWithValue("$acceptDelay", notice.AcceptDelaySeconds);
|
||||
return command.ExecuteNonQuery();
|
||||
});
|
||||
}
|
||||
@@ -184,6 +186,7 @@ public class SqliteNoticeStore : INoticeStore
|
||||
Title = reader.GetString(1),
|
||||
Body = reader.GetString(2),
|
||||
RequireAccept = reader.GetBoolean(3),
|
||||
AcceptDelaySeconds = reader.GetInt32(10),
|
||||
Enabled = reader.GetBoolean(4),
|
||||
Target = new NoticeTarget
|
||||
{
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
/*
|
||||
* Herald client for jellyfin-web.
|
||||
* Shows pending notices one at a time. No dependencies; ES5 on purpose, some TV web views are old.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
if (window.__heraldClient) {
|
||||
return;
|
||||
}
|
||||
window.__heraldClient = true;
|
||||
|
||||
var CHECK_INTERVAL_MS = 10 * 60 * 1000;
|
||||
var SESSION_POLL_MS = 3000;
|
||||
var SAFE_LINK = /^(https?:\/\/|mailto:)/i;
|
||||
|
||||
var userId = null;
|
||||
var lastCheck = 0;
|
||||
var checking = false;
|
||||
var queue = [];
|
||||
var open = null;
|
||||
|
||||
// ---------------------------------------------------------------- session
|
||||
|
||||
function currentUserId() {
|
||||
try {
|
||||
var client = window.ApiClient;
|
||||
if (!client || typeof client.getCurrentUserId !== 'function') {
|
||||
return null;
|
||||
}
|
||||
var token = typeof client.accessToken === 'function' ? client.accessToken() : null;
|
||||
return token ? (client.getCurrentUserId() || null) : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function send(method, path, body) {
|
||||
var client = window.ApiClient;
|
||||
var options = { type: method, url: client.getUrl(path) };
|
||||
if (body) {
|
||||
options.data = JSON.stringify(body);
|
||||
options.contentType = 'application/json';
|
||||
}
|
||||
if (method === 'GET') {
|
||||
options.dataType = 'json';
|
||||
}
|
||||
return client.ajax(options);
|
||||
}
|
||||
|
||||
// Runs on a short local timer. It only talks to the server after a login or
|
||||
// user switch, and otherwise once per CHECK_INTERVAL_MS.
|
||||
function tick() {
|
||||
var id = currentUserId();
|
||||
if (id !== userId) {
|
||||
userId = id;
|
||||
queue = [];
|
||||
closeOpen();
|
||||
if (id) {
|
||||
check();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (id && !document.hidden && Date.now() - lastCheck >= CHECK_INTERVAL_MS) {
|
||||
check();
|
||||
}
|
||||
}
|
||||
|
||||
function check() {
|
||||
if (checking || !userId) {
|
||||
return;
|
||||
}
|
||||
checking = true;
|
||||
lastCheck = Date.now();
|
||||
var askedFor = userId;
|
||||
|
||||
send('GET', 'Herald/Notices/Pending').then(function (notices) {
|
||||
checking = false;
|
||||
if (askedFor !== userId || !notices || !notices.length) {
|
||||
return;
|
||||
}
|
||||
queue = notices.filter(function (n) {
|
||||
return !open || open.notice.Id !== n.Id || open.notice.Revision !== n.Revision;
|
||||
});
|
||||
showNext();
|
||||
}, function () {
|
||||
checking = false;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- content
|
||||
|
||||
function appendText(parent, text) {
|
||||
if (text) {
|
||||
parent.appendChild(document.createTextNode(text));
|
||||
}
|
||||
}
|
||||
|
||||
// Bold, italic and links. Everything ends up as text nodes or elements
|
||||
// created here; the notice body is never parsed as HTML.
|
||||
function appendInline(parent, text) {
|
||||
var pattern = /\*\*([^*]+?)\*\*|\*([^*\s][^*]*?)\*|(^|[^\w])_([^_\s][^_]*?)_(?!\w)|\[([^\]]+)\]\(([^)\s]+)\)/g;
|
||||
var last = 0;
|
||||
var match;
|
||||
|
||||
while ((match = pattern.exec(text)) !== null) {
|
||||
appendText(parent, text.slice(last, match.index));
|
||||
last = pattern.lastIndex;
|
||||
|
||||
if (match[1] !== undefined) {
|
||||
appendInline(parent.appendChild(document.createElement('strong')), match[1]);
|
||||
} else if (match[2] !== undefined) {
|
||||
appendInline(parent.appendChild(document.createElement('em')), match[2]);
|
||||
} else if (match[4] !== undefined) {
|
||||
appendText(parent, match[3]);
|
||||
appendInline(parent.appendChild(document.createElement('em')), match[4]);
|
||||
} else if (SAFE_LINK.test(match[6])) {
|
||||
var link = document.createElement('a');
|
||||
link.href = match[6];
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.className = 'heraldLink';
|
||||
appendInline(link, match[5]);
|
||||
parent.appendChild(link);
|
||||
} else {
|
||||
appendText(parent, match[0]);
|
||||
}
|
||||
}
|
||||
|
||||
appendText(parent, text.slice(last));
|
||||
}
|
||||
|
||||
function appendBody(parent, body) {
|
||||
var lines = String(body || '').replace(/\r\n?/g, '\n').split('\n');
|
||||
var block = null;
|
||||
var blockType = null;
|
||||
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
var line = lines[i];
|
||||
var bullet = /^\s*[-*]\s+(.*)$/.exec(line);
|
||||
var numbered = /^\s*\d+[.)]\s+(.*)$/.exec(line);
|
||||
|
||||
if (!line.trim()) {
|
||||
block = null;
|
||||
blockType = null;
|
||||
} else if (bullet || numbered) {
|
||||
var type = bullet ? 'ul' : 'ol';
|
||||
if (blockType !== type) {
|
||||
block = parent.appendChild(document.createElement(type));
|
||||
blockType = type;
|
||||
}
|
||||
appendInline(block.appendChild(document.createElement('li')), (bullet || numbered)[1]);
|
||||
} else {
|
||||
if (blockType !== 'p') {
|
||||
block = parent.appendChild(document.createElement('p'));
|
||||
blockType = 'p';
|
||||
} else {
|
||||
block.appendChild(document.createElement('br'));
|
||||
}
|
||||
appendInline(block, line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- modal
|
||||
|
||||
var CSS = [
|
||||
'.heraldBackdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:999990;display:flex;align-items:center;justify-content:center;',
|
||||
'padding:1.2em;box-sizing:border-box;background:rgba(0,0,0,.66);opacity:0;transition:opacity .14s ease-out}',
|
||||
'.heraldBackdrop.heraldIn{opacity:1}',
|
||||
// Fallback surface for themes without a ".dialog" rule; zero specificity so the theme wins when it has one.
|
||||
':where(.heraldSheet){background-color:var(--jf-palette-background-paper,#202020)}',
|
||||
'.heraldSheet.heraldSheet{position:relative;display:flex;flex-direction:column;width:100%;max-width:34em;max-height:86vh;margin:0;padding:0;',
|
||||
'box-sizing:border-box;border:1px solid rgba(128,128,128,.28);border-radius:.3em;overflow:hidden;',
|
||||
'box-shadow:0 1.2em 3em rgba(0,0,0,.55);transform:translateY(.6em);transition:transform .16s ease-out}',
|
||||
'.heraldIn .heraldSheet{transform:none}',
|
||||
'.heraldMast{flex:none;padding:1.5em 1.7em 0}',
|
||||
'.heraldKicker{display:flex;justify-content:space-between;margin:0;font-size:.74em;font-weight:600;letter-spacing:.16em;text-transform:uppercase;opacity:.7}',
|
||||
'.heraldRule{height:.3em;margin:.6em 0 1em;border-top:.12em solid currentColor;border-bottom:1px solid currentColor;opacity:.42}',
|
||||
'.heraldTitle{margin:0;font-size:1.5em;font-weight:600;line-height:1.22;overflow-wrap:anywhere}',
|
||||
'.heraldBody{flex:1 1 auto;min-height:0;overflow-y:auto;padding:.9em 1.7em .3em;line-height:1.55;overflow-wrap:anywhere}',
|
||||
'.heraldBody p{margin:0 0 .85em}',
|
||||
'.heraldBody ul,.heraldBody ol{margin:0 0 .85em;padding-left:1.35em}',
|
||||
'.heraldBody li{margin:.2em 0}',
|
||||
'.heraldLink{color:var(--jf-palette-primary-main,#00a4dc);text-decoration:underline}',
|
||||
'.heraldFoot{flex:none;display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:.4em 1em;padding:.7em 1.7em 1.3em}',
|
||||
'.heraldError{flex:1 1 12em;margin:0;font-size:.9em;color:var(--jf-palette-error-main,#e2574c)}',
|
||||
'.heraldButton.heraldButton{flex:none;margin:0;min-width:8.5em;justify-content:center;text-align:center;font-variant-numeric:tabular-nums}',
|
||||
'.heraldButton.heraldWaiting{opacity:.5;cursor:default}',
|
||||
'@media (max-width:30em){.heraldBackdrop{padding:.6em;align-items:flex-end}.heraldMast{padding:1.2em 1.2em 0}',
|
||||
'.heraldBody{padding:.8em 1.2em .2em}.heraldFoot{padding:.6em 1.2em 1.1em}.heraldButton.heraldButton{flex:1 1 100%}}',
|
||||
'@media (prefers-reduced-motion:reduce){.heraldBackdrop,.heraldSheet.heraldSheet{transition:none}}'
|
||||
].join('');
|
||||
|
||||
function ensureStyle() {
|
||||
if (!document.getElementById('heraldStyle')) {
|
||||
var style = document.createElement('style');
|
||||
style.id = 'heraldStyle';
|
||||
style.textContent = CSS;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
|
||||
function element(tag, className, text) {
|
||||
var node = document.createElement(tag);
|
||||
if (className) {
|
||||
node.className = className;
|
||||
}
|
||||
if (text) {
|
||||
node.textContent = text;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
function showNext() {
|
||||
if (open || !queue.length || !userId) {
|
||||
return;
|
||||
}
|
||||
show(queue.shift());
|
||||
}
|
||||
|
||||
function show(notice) {
|
||||
ensureStyle();
|
||||
|
||||
var mustAccept = !!notice.RequireAccept;
|
||||
var titleId = 'heraldTitle-' + notice.Id;
|
||||
|
||||
var backdrop = element('div', 'heraldBackdrop');
|
||||
// "dialog" and the button classes are jellyfin-web's own, so the active theme colors them.
|
||||
var sheet = element('div', 'heraldSheet dialog');
|
||||
sheet.tabIndex = -1;
|
||||
sheet.setAttribute('role', mustAccept ? 'alertdialog' : 'dialog');
|
||||
sheet.setAttribute('aria-modal', 'true');
|
||||
sheet.setAttribute('aria-labelledby', titleId);
|
||||
|
||||
var mast = element('div', 'heraldMast');
|
||||
var kicker = element('p', 'heraldKicker');
|
||||
kicker.appendChild(element('span', null, mustAccept ? 'Please confirm' : 'Notice'));
|
||||
if (queue.length) {
|
||||
kicker.appendChild(element('span', null, (queue.length) + ' more'));
|
||||
}
|
||||
mast.appendChild(kicker);
|
||||
mast.appendChild(element('div', 'heraldRule'));
|
||||
var title = element('h2', 'heraldTitle', notice.Title);
|
||||
title.id = titleId;
|
||||
mast.appendChild(title);
|
||||
|
||||
var body = element('div', 'heraldBody');
|
||||
appendBody(body, notice.Body);
|
||||
|
||||
var foot = element('div', 'heraldFoot');
|
||||
var error = element('p', 'heraldError');
|
||||
error.setAttribute('role', 'alert');
|
||||
var button = element('button', 'heraldButton raised button-submit emby-button', mustAccept ? 'Accept' : 'Close');
|
||||
button.type = 'button';
|
||||
foot.appendChild(error);
|
||||
foot.appendChild(button);
|
||||
|
||||
sheet.appendChild(mast);
|
||||
sheet.appendChild(body);
|
||||
sheet.appendChild(foot);
|
||||
backdrop.appendChild(sheet);
|
||||
|
||||
var state = {
|
||||
notice: notice,
|
||||
backdrop: backdrop,
|
||||
button: button,
|
||||
error: error,
|
||||
sending: false,
|
||||
timer: null,
|
||||
previousFocus: document.activeElement,
|
||||
onKey: null
|
||||
};
|
||||
|
||||
button.addEventListener('click', function () {
|
||||
respond(state, mustAccept ? 'Accepted' : 'Dismissed');
|
||||
});
|
||||
|
||||
backdrop.addEventListener('click', function (e) {
|
||||
if (e.target === backdrop && !mustAccept) {
|
||||
respond(state, 'Dismissed');
|
||||
}
|
||||
});
|
||||
|
||||
state.onKey = function (e) {
|
||||
if (e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) {
|
||||
// Keep jellyfin-web from treating it as "back".
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!mustAccept) {
|
||||
respond(state, 'Dismissed');
|
||||
}
|
||||
} else if (e.key === 'Tab' || e.keyCode === 9) {
|
||||
keepFocusInside(e, sheet);
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', state.onKey, true);
|
||||
|
||||
open = state;
|
||||
document.body.appendChild(backdrop);
|
||||
// Two frames so the transition has a starting state to move from.
|
||||
requestAnimationFrame(function () {
|
||||
requestAnimationFrame(function () {
|
||||
backdrop.classList.add('heraldIn');
|
||||
});
|
||||
});
|
||||
var wait = mustAccept ? Math.floor(Number(notice.AcceptDelaySeconds) || 0) : 0;
|
||||
if (wait > 0) {
|
||||
holdButton(state, wait);
|
||||
sheet.focus();
|
||||
} else {
|
||||
button.focus();
|
||||
}
|
||||
}
|
||||
|
||||
// Keeps the button locked for the given number of seconds. Only time with the tab in view counts.
|
||||
function holdButton(state, seconds) {
|
||||
var button = state.button;
|
||||
var label = button.textContent;
|
||||
var left = seconds;
|
||||
|
||||
function paint() {
|
||||
button.textContent = label + ' (' + left + ')';
|
||||
}
|
||||
|
||||
button.disabled = true;
|
||||
button.classList.add('heraldWaiting');
|
||||
paint();
|
||||
|
||||
state.timer = setInterval(function () {
|
||||
if (document.hidden) {
|
||||
return;
|
||||
}
|
||||
left--;
|
||||
if (left > 0) {
|
||||
paint();
|
||||
return;
|
||||
}
|
||||
clearInterval(state.timer);
|
||||
state.timer = null;
|
||||
button.textContent = label;
|
||||
button.classList.remove('heraldWaiting');
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function keepFocusInside(e, sheet) {
|
||||
var items = sheet.querySelectorAll('a[href],button');
|
||||
if (!items.length) {
|
||||
return;
|
||||
}
|
||||
var first = items[0];
|
||||
var last = items[items.length - 1];
|
||||
if (!sheet.contains(document.activeElement)) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
} else if (e.shiftKey && document.activeElement === first) {
|
||||
e.preventDefault();
|
||||
last.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function respond(state, action) {
|
||||
if (state.sending || state.timer || open !== state) {
|
||||
return;
|
||||
}
|
||||
state.sending = true;
|
||||
state.button.disabled = true;
|
||||
state.error.textContent = '';
|
||||
|
||||
var path = 'Herald/Notices/' + encodeURIComponent(state.notice.Id) + '/Ack';
|
||||
send('POST', path, { revision: state.notice.Revision, action: action }).then(function () {
|
||||
closeOpen();
|
||||
showNext();
|
||||
}, function (response) {
|
||||
var status = response && response.status;
|
||||
if (status === 404 || status === 409) {
|
||||
// Changed or withdrawn while it was on screen: ask the server what is current.
|
||||
closeOpen();
|
||||
queue = [];
|
||||
check();
|
||||
} else if (action === 'Dismissed') {
|
||||
// Not stored, so it comes back with the next check. Do not hold the user up.
|
||||
closeOpen();
|
||||
showNext();
|
||||
} else {
|
||||
state.sending = false;
|
||||
state.button.disabled = false;
|
||||
state.error.textContent = 'Could not save your answer. Please try again.';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function closeOpen() {
|
||||
var state = open;
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
open = null;
|
||||
if (state.timer) {
|
||||
clearInterval(state.timer);
|
||||
state.timer = null;
|
||||
}
|
||||
document.removeEventListener('keydown', state.onKey, true);
|
||||
if (state.backdrop.parentNode) {
|
||||
state.backdrop.parentNode.removeChild(state.backdrop);
|
||||
}
|
||||
try {
|
||||
if (state.previousFocus && document.contains(state.previousFocus)) {
|
||||
state.previousFocus.focus();
|
||||
}
|
||||
} catch (e) {
|
||||
// focus is a courtesy
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- start
|
||||
|
||||
setInterval(tick, SESSION_POLL_MS);
|
||||
document.addEventListener('visibilitychange', function () {
|
||||
if (!document.hidden) {
|
||||
tick();
|
||||
}
|
||||
});
|
||||
tick();
|
||||
})();
|
||||
@@ -1,425 +1,205 @@
|
||||
# So you want to make a Jellyfin plugin
|
||||
# Herald
|
||||
|
||||
Awesome! This guide is for you. Jellyfin plugins are written using the dotnet standard framework. What that means is you can write them in any language that implements the CLI or the DLI and can compile to net8.0. The examples on this page are in C# because that is what most of Jellyfin is written in, but F#, Visual Basic, and IronPython should all be compatible once compiled.
|
||||
A Jellyfin plugin for two small jobs:
|
||||
|
||||
## 0. Things you need to get started
|
||||
- **Notices.** Admins write a message, every addressed user sees it once as a popup in the web client. A notice can require an explicit "Accept", and the admin can see who responded and who has not.
|
||||
- **Watch-time stats.** Approximate time each user spent watching over the last weeks, as a sortable table in the dashboard.
|
||||
|
||||
- [Dotnet SDK 9.0](https://dotnet.microsoft.com/en-us/download/dotnet)
|
||||
Built for Jellyfin **10.11.x** (compiled against 10.11.11, `net9.0`).
|
||||
|
||||
- An editor of your choice. Some free choices are:
|
||||
## Known limitation: web client only
|
||||
|
||||
[Visual Studio Code](https://code.visualstudio.com)
|
||||
Notices are shown by a script running inside **jellyfin-web**. That covers the browser, Jellyfin Media Player / the desktop app, and mobile apps as far as they wrap the web client.
|
||||
|
||||
[Visual Studio Community Edition](https://visualstudio.microsoft.com/downloads)
|
||||
**Native clients never show notices**: Android TV, Swiftfin, Kodi, Roku, Findroid, Infuse and similar apps do not load jellyfin-web. A user who only uses such a client stays in the "not yet" list of a notice until they open the web client once. Do not rely on a must-accept notice to gate access; it does not block anything on the server.
|
||||
|
||||
[Mono Develop](https://www.monodevelop.com)
|
||||
Watch-time stats are collected on the server and cover all clients.
|
||||
|
||||
## 0.5. Quickstarts
|
||||
## Installation
|
||||
|
||||
We have a number of quickstart options available to speed you along the way.
|
||||
### From a plugin repository
|
||||
|
||||
- [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. In Jellyfin: **Dashboard → Plugins → Manage Repositories → New Repository**, enter `https://git.joshicodes.de/JoshiCodes/jellyfin-herald/raw/branch/main/manifest.json`.
|
||||
2. Install **Herald** from the catalogue and restart the server.
|
||||
|
||||
- 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)
|
||||
### Manually
|
||||
|
||||
```shell
|
||||
dotnet new -i /path/to/templatefolder
|
||||
```
|
||||
1. Take `herald_<version>.zip` from a release, or build it yourself (see [Building](#building)).
|
||||
2. Unpack it into `plugins/Herald_<version>/` inside the Jellyfin data directory, for example `/config/plugins/Herald_1.0.0.0/` in the official container. The folder holds `Jellyfin.Plugin.Herald.dll` and `meta.json`.
|
||||
3. Restart Jellyfin. The log shows `Loaded plugin: Herald`.
|
||||
|
||||
- Run this command then skip to step 4
|
||||
Herald has its own entry in the dashboard sidebar, in the **Plugins** section. The same page opens from **Dashboard → Plugins → Herald**.
|
||||
|
||||
```shell
|
||||
dotnet new Jellyfin-plugin -name MyPlugin
|
||||
```
|
||||
## Getting the popup into the web client
|
||||
|
||||
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.
|
||||
The server part works on its own. For notices to appear, the client script (`/Herald/client.js`) has to be loaded by jellyfin-web. There are three ways.
|
||||
|
||||
## 1. Initialize Your Project
|
||||
### File Transformation (recommended)
|
||||
|
||||
Make a new dotnet standard project with the following command, it will make a directory for itself.
|
||||
Install the [File Transformation](https://github.com/IAmParadox27/jellyfin-plugin-file-transformation) plugin (repository URL `https://www.iamparadox.dev/jellyfin/plugins/manifest.json`) and restart. Herald registers itself at startup and File Transformation adds one script tag to the `index.html` it serves. Nothing on disk is changed.
|
||||
|
||||
```shell
|
||||
dotnet new classlib -f net9.0 -n MyJellyfinPlugin
|
||||
The log tells you which case you are in:
|
||||
|
||||
```
|
||||
Registered the Herald client script with File Transformation 3.0.3.0
|
||||
```
|
||||
|
||||
Now add the Jellyfin shared libraries.
|
||||
or, if it is missing:
|
||||
|
||||
```shell
|
||||
dotnet add package Jellyfin.Model
|
||||
dotnet add package Jellyfin.Controller
|
||||
```
|
||||
The File Transformation plugin is not installed, so the Herald client script is not injected ...
|
||||
```
|
||||
|
||||
You have an autogenerated Class1.cs file. You won't be needing this, so go ahead and delete it.
|
||||
File Transformation releases are tied to exact Jellyfin versions, so pick the build that matches your 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.
|
||||
To check the result, open `http://<server>/web/index.html` and look for `data-herald-client` in the source. Other plugins that use File Transformation (MediaBar, Home Screen Sections, Jellyfin Enhanced and so on) can be installed alongside.
|
||||
|
||||
```xml
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Jellyfin.Controller" Version="10.11.5">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Jellyfin.Model" Version="10.11.5">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
### Fallback: JavaScript Injector
|
||||
|
||||
With the [JavaScript Injector](https://github.com/n00bcodr/Jellyfin-JavaScript-Injector) plugin, add a script with this content and enable it:
|
||||
|
||||
```js
|
||||
(function () {
|
||||
var script = document.createElement('script');
|
||||
script.src = '../Herald/client.js';
|
||||
script.defer = true;
|
||||
document.head.appendChild(script);
|
||||
})();
|
||||
```
|
||||
|
||||
Note: Ensure the package reference version matches the install version of jellyfin server, otherwise the plugin will show as NotSupported.
|
||||
### Fallback: edit index.html
|
||||
|
||||
## 2. Set Up the Basics
|
||||
Add this line right before `</body>` in `index.html` of your jellyfin-web folder (`/usr/share/jellyfin/web/` on most Linux packages, `/jellyfin/jellyfin-web/` in the official container):
|
||||
|
||||
There are a few mandatory classes you'll need for a plugin so we need to make them.
|
||||
|
||||
### PluginConfiguration
|
||||
|
||||
Create a folder named "Configuration", and a PluginConfiguration.cs file inside.
|
||||
|
||||
You can call it whatever you'd like really. This class is used to hold settings your plugin might need. We can leave it empty for now. This class should inherit from `MediaBrowser.Model.Plugins.BasePluginConfiguration`
|
||||
|
||||
It should look something like the following:
|
||||
|
||||
```csharp
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace MyJellyfinPlugin.Configuration;
|
||||
class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
|
||||
}
|
||||
```html
|
||||
<script defer src="../Herald/client.js"></script>
|
||||
```
|
||||
|
||||
### Plugin
|
||||
This is overwritten by every Jellyfin update.
|
||||
|
||||
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>`
|
||||
Jellyfin 10.11 has no "Custom HTML" setting in the dashboard. The branding page only takes CSS and a login disclaimer, neither of which can load a script.
|
||||
|
||||
It should look something like the following:
|
||||
## Using it
|
||||
|
||||
```csharp
|
||||
using MediaBrowser.Common.Plugins;
|
||||
using MyJellyfinPlugin.Configuration;
|
||||
**Notices tab**
|
||||
|
||||
namespace MyJellyfinPlugin;
|
||||
- *New notice*: title, message, whether it has to be accepted, whether it is enabled, and who gets it (all users, or users picked from a list).
|
||||
- *Wait before "Accept" can be clicked*: for a must-accept notice, the number of seconds (0 to 600) the *Accept* button stays locked. It shows a countdown, and only time with the tab in view counts.
|
||||
- The message is plain text and line breaks are kept. A small Markdown subset is understood: `**bold**`, `*italic*`, `[text](https://…)`, and lines starting with `- ` or `1. ` as lists. HTML is not interpreted; it shows up as text.
|
||||
- *Enabled* switches a notice off without deleting it.
|
||||
- *Re-show to everyone* shows the notice again to all addressed users, including those who already responded. Editing a notice does **not** do that.
|
||||
- *Responses* lists who accepted or dismissed and when, and who is still missing.
|
||||
|
||||
class Plugin : BasePlugin<PluginConfiguration>
|
||||
{
|
||||
**What users see**
|
||||
|
||||
}
|
||||
One notice at a time, oldest first. A normal notice has a *Close* button; clicking outside or pressing Escape also closes it and counts as dismissed. A must-accept notice has only an *Accept* button; clicking outside and Escape do nothing. If a wait is set, the button reads *Accept (12)* and unlocks when the countdown reaches zero. The script asks for new notices after login, after a user switch, and then every 10 minutes while the tab is visible.
|
||||
|
||||
**Stats tab**
|
||||
|
||||
Per user: watch time over the last 7 and 30 days, plays in the last 30 days, and last activity. Click a column header to sort.
|
||||
|
||||
## API
|
||||
|
||||
All routes are under `/Herald`. Authentication is Jellyfin's normal `Authorization: MediaBrowser Token="…"` header. Responses use Jellyfin's usual PascalCase JSON; request bodies are accepted in any casing. Ids are GUIDs.
|
||||
|
||||
| Method | Route | Access | Purpose |
|
||||
| --- | --- | --- | --- |
|
||||
| `GET` | `/Herald/client.js` | anyone | The client script. |
|
||||
| `GET` | `/Herald/Notices/Pending` | signed-in user | Enabled notices addressed to the caller that they have not responded to at the current revision, oldest first. |
|
||||
| `POST` | `/Herald/Notices/{id}/Ack` | signed-in user | Body `{ "revision": 1, "action": "Accepted" }` (`Accepted` or `Dismissed`). `204` on success, `400` if a must-accept notice is dismissed, `404` if the notice is gone or not addressed to the caller, `409` if the revision is outdated. |
|
||||
| `GET` | `/Herald/Notices` | admin | All notices. |
|
||||
| `GET` | `/Herald/Notices/{id}` | admin | One notice. |
|
||||
| `POST` | `/Herald/Notices` | admin | Create. Body: `Title`, `Body`, `RequireAccept`, `AcceptDelaySeconds` (0 to 600, ignored unless `RequireAccept`), `Enabled`, `Target: { AllUsers, UserIds }`. |
|
||||
| `PUT` | `/Herald/Notices/{id}` | admin | Update, same body. Keeps the revision. |
|
||||
| `DELETE` | `/Herald/Notices/{id}` | admin | Delete the notice and its responses. |
|
||||
| `POST` | `/Herald/Notices/{id}/Reshow` | admin | Bump the revision. |
|
||||
| `GET` | `/Herald/Notices/{id}/Acks` | admin | Responses to the current revision (`UserName`, `Action`, `Timestamp`) and the addressed users still pending. |
|
||||
| `GET` | `/Herald/Stats?days=30` | admin | Per user: `UserName`, `WatchedSeconds`, `WatchedHours`, `PlayCount`, `LastActivity`. `days` is 1 to 90 and includes today. |
|
||||
|
||||
A notice looks like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"Id": "0aadc31081754558a45ffc79dd49a820",
|
||||
"Title": "House rules",
|
||||
"Body": "Be nice.",
|
||||
"RequireAccept": true,
|
||||
"AcceptDelaySeconds": 15,
|
||||
"Enabled": true,
|
||||
"Target": { "AllUsers": false, "UserIds": ["21b3bac6acfe496bbca02a21c21e36d4"] },
|
||||
"Revision": 2,
|
||||
"CreatedAt": "2026-11-13T16:57:12.5166578Z",
|
||||
"UpdatedAt": "2026-11-13T16:57:12.9794785Z"
|
||||
}
|
||||
```
|
||||
|
||||
Note: If you called your PluginConfiguration class something different, you need to put that between the <>
|
||||
## How the stats are calculated
|
||||
|
||||
### Implement Required Properties
|
||||
Clients report to the server when playback starts, every few seconds while it runs, and when it stops. Herald listens to those reports:
|
||||
|
||||
The Plugin class needs a few properties implemented before it can work correctly.
|
||||
- The time between two consecutive reports of the same playback is added to the user's total, measured on the server's clock.
|
||||
- Nothing is added for a stretch that began with a "paused" report.
|
||||
- A single gap adds at most 60 seconds. After 5 minutes without a report the playback counts as closed and the gap adds nothing.
|
||||
- Each playback start counts as one play.
|
||||
- Only one row per user and day is stored (watched seconds, plays, last activity). There is no per-item or per-event history. Rows older than 90 days are deleted by the scheduled task *Clean up Herald watch-time stats*, daily at 03:30.
|
||||
- "Day" means the server's local day. Time that crosses midnight is split between both days.
|
||||
|
||||
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.
|
||||
Where the numbers are off:
|
||||
|
||||
```csharp
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer){}
|
||||
public override string Name => throw new System.NotImplementedException();
|
||||
public override Guid Id => Guid.Parse("");
|
||||
- **It measures playing, not watching.** A film running in an empty room counts in full.
|
||||
- **Buffering counts** as long as the client keeps reporting and does not report itself as paused.
|
||||
- **Sparse reporters are undercounted.** A client that reports less often than once a minute only gets 60 seconds per report.
|
||||
- **Playback speed is ignored.** An hour at 2× is an hour of watch time for two hours of content.
|
||||
- **Plays are starts, not completions.** Opening a film for ten seconds is a play. Each episode of a binge is a play.
|
||||
- **Lost stop reports** (app killed, network gone) lose up to the last reporting interval, usually a few seconds.
|
||||
- **Sessions with several users attached** credit the full time to each of them.
|
||||
- **Offline playback** of downloaded media is invisible to the server.
|
||||
- Counting starts when the plugin is installed. Nothing is back-filled from Jellyfin's play history, and time zone changes of the server shift which day later playback is booked on.
|
||||
|
||||
## Data
|
||||
|
||||
Everything is in one SQLite file, `herald/herald.db` in Jellyfin's data directory (`/config/data/herald/herald.db` in the official container). It holds the notices, the responses and the daily watch-time rows. Deleting the file while the server is stopped resets the plugin.
|
||||
|
||||
The plugin uses the SQLite library that ships with Jellyfin and bundles none of its own.
|
||||
|
||||
## Building
|
||||
|
||||
Requires the .NET 9 SDK.
|
||||
|
||||
```sh
|
||||
dotnet build -c Release
|
||||
dotnet test -c Release
|
||||
```
|
||||
|
||||
## 3. Customize Plugin Information
|
||||
Package with [jprm](https://github.com/oddstr13/jellyfin-plugin-repository-manager):
|
||||
|
||||
You need to populate some of your plugin's information. Go ahead a put in a string of the Name you've overridden name, and generate a GUID
|
||||
|
||||
- **Windows Users**: you can use the Powershell command `New-Guid`, `[guid]::NewGuid()` or the Visual Studio GUID generator
|
||||
|
||||
- **Linux and OS X Users**: you can use the Powershell Core command `New-Guid` or this command from your shell of choice:
|
||||
|
||||
```shell
|
||||
od -x /dev/urandom | head -n1 | awk '{OFS="-"; srand($6); sub(/./,"4",$5); sub(/./,substr("89ab",1+rand()*4,1),$6); print $2$3,$4,$5,$6,$7$8$9}'
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```shell
|
||||
uuidgen
|
||||
```
|
||||
|
||||
- Place that guid inside the `Guid.Parse("")` quotes to define your plugin's ID.
|
||||
|
||||
## 4. Adding Functionality
|
||||
|
||||
Congratulations, you now have everything you need for a perfectly functional functionless Jellyfin plugin! You can try it out right now if you'd like by compiling it, then placing the dll you generate in a subfolder (named after your plugin for example) within the plugins folder under your Jellyfin directory (Normally C:\Users\{YourUserName}\AppData\Local\jellyfin\plugins). If you want to try and hook it up to a debugger make sure you copy the generated PDB file alongside it.
|
||||
|
||||
Most people aren't satisfied with just having an entry in a menu for their plugin, most people want to have some functionality, so lets look at how to add it.
|
||||
|
||||
### 4a. Implement Interfaces
|
||||
|
||||
If the functionality you are trying to add is functionality related to something that Jellyfin has an interface for you're in luck. Jellyfin uses some automatic discovery and injection to allow any interfaces you implement in your plugin to be available in Jellyfin.
|
||||
|
||||
Here's some interfaces you could implement for common use cases:
|
||||
|
||||
- **IAuthenticationProvider** - Allows you to add an authentication provider that can authenticate a user based on a name and a password, but that doesn't expect to deal with local users.
|
||||
- **IBaseItemComparer** - Allows you to add sorting rules for dealing with media that will show up in sort menus
|
||||
- **IIntroProvider** - Allows you to play a piece of media before another piece of media (i.e. a trailer before a movie, or a network bumper before an episode of a show)
|
||||
- **IItemResolver** - Allows you to define custom media types
|
||||
- **ILibraryPostScanTask** - Allows you to define a task that fires after scanning a library
|
||||
- **IMetadataSaver** - Allows you to define a metadata standard that Jellyfin can use to write metadata
|
||||
- **IResolverIgnoreRule** - Allows you to define subpaths that are ignored by media resolvers for use with another function (i.e. you wanted to have a theme song for each tv series stored in a subfolder that could be accessed by your plugin for playback in a menu).
|
||||
- **IScheduledTask** - Allows you to create a scheduled task that will appear in the scheduled task lists on the dashboard.
|
||||
|
||||
There are loads of other interfaces that can be used, but you'll need to poke around the API to get some info. If you're an expert on a particular interface, you should help [contribute some documentation](https://docs.jellyfin.org/general/contributing/index.html)!
|
||||
|
||||
### 4b. Use plugin aimed interfaces to add custom functionality
|
||||
|
||||
If your plugin doesn't fit perfectly neatly into a predefined interface, never fear, there are a set of interfaces and classes that allow your plugin to extend Jellyfin any which way you please. Here's a quick overview on how to use them
|
||||
|
||||
- **IPluginConfigurationPage** - Allows you to have a plugin config page on the dashboard. If you used one of the quickstart example projects, a premade page with some useful components to work with has been created for you! If not you can check out this guide here for how to whip one up.
|
||||
|
||||
**IPluginServiceRegistrator** - Will be located by Jellyfin at server startup and allows you to add services to the DI container to allow for injection in your plugin's classes later.
|
||||
|
||||
- **IHostedService** - Allows you to run code as a background task that will be started at program startup and will remain in memory. See [Microsoft's documentation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-9.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-9.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
|
||||
```sh
|
||||
pip install jprm
|
||||
mkdir -p artifacts
|
||||
jprm plugin build . --output artifacts
|
||||
```
|
||||
|
||||
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.
|
||||
This writes `artifacts/herald_<version>.zip`. The Jellyfin version, target framework and SQLite version are set in `Directory.Build.props`; `targetAbi` is in `build.yaml`.
|
||||
|
||||
### 6.a Set Up Debugging on Visual Studio
|
||||
## Releasing
|
||||
|
||||
Visual Studio allows developers to connect to other processes and debug them, setting breakpoints and inspecting the variables of the program. We can set this up following this steps:
|
||||
On this section we will explain how to set up our solution to enable debugging before the server starts.
|
||||
The version lives in `build.yaml` (`version`) and `Directory.Build.props` (`Version`, `AssemblyVersion`, `FileVersion`); keep them equal, the workflow fails otherwise. Put the release notes in `changelog` in `build.yaml`.
|
||||
|
||||
1. Right-click on the solution, And click on Add -> Existing Project...
|
||||
2. Locate Jellyfin executable in your installation folder and click on 'Open'. It is called `Jellyfin.exe`. Now The solution will have a new "Project" called Jellyfin. This is the executable, not the source code of Jellyfin.
|
||||
3. Right-click on this new project and click on 'Set up as Startup Project'
|
||||
4. Right-click on this new project and click on 'Properties'
|
||||
5. Make sure that the 'Attach' parameter is set to 'No'
|
||||
Every push to `main` builds and tests. If the version has no `v<version>` tag yet, the workflow (`.gitea/workflows/build.yaml`, Gitea Actions) also creates that tag and a release with the plugin zip, adds the version to `manifest.json` and commits that file back to `main`. So a release is: bump the version, push, and pull the manifest commit afterwards.
|
||||
|
||||
From now on, everytime you click on start from Visual Studio, it will start Jellyfin attached to the debugger!
|
||||
## Hosting your own repository
|
||||
|
||||
The only thing left to do is to compile the project as it is specified a few lines above and you are done.
|
||||
The `manifest.json` in the source tree is a complete plugin repository; the URL under [Installation](#installation) is its raw link on `main`. A copy is attached to every release.
|
||||
|
||||
### 6.b Automate the Setup on Visual Studio Code
|
||||
To host it elsewhere, build the manifest yourself:
|
||||
|
||||
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.
|
||||
```sh
|
||||
jprm repo init ./repo
|
||||
jprm repo add --plugin-url https://example.org/herald/herald_1.0.0.0.zip ./repo artifacts/herald_1.0.0.0.zip
|
||||
```
|
||||
|
||||
A full example, which aims to be portable may be found in this repo's `.vscode` folder.
|
||||
Serve the resulting `manifest.json` and the zip over HTTP(S) and add the manifest URL in Jellyfin.
|
||||
|
||||
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`
|
||||
## License
|
||||
|
||||
1. Create a `settings.json` file inside your `.vscode` folder, to specify common options specific to your local setup.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// jellyfinDir : The directory of the cloned jellyfin server project
|
||||
// This needs to be built once before it can be used
|
||||
"jellyfinDir" : "${workspaceFolder}/../jellyfin/Jellyfin.Server",
|
||||
// jellyfinWebDir : The directory of the cloned jellyfin-web project
|
||||
// This needs to be built once before it can be used
|
||||
"jellyfinWebDir" : "${workspaceFolder}/../jellyfin-web",
|
||||
// jellyfinDataDir : the root data directory for a running jellyfin instance
|
||||
// This is where jellyfin stores its configs, plugins, metadata etc
|
||||
// This is platform specific by default, but on Windows defaults to
|
||||
// ${env:LOCALAPPDATA}/jellyfin
|
||||
"jellyfinDataDir" : "${env:LOCALAPPDATA}/jellyfin",
|
||||
// The name of the plugin
|
||||
"pluginName" : "Jellyfin.Plugin.Template",
|
||||
}
|
||||
```
|
||||
|
||||
1. To automate the launch process, create a new `launch.json` file for C# projects inside the `.vscode` folder. The example below shows only the relevant parts of the file. Adjustments to your specific setup and operating system may be required.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Paths and plugin names are configured in settings.json
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "coreclr",
|
||||
"name": "Launch",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build-and-copy",
|
||||
"program": "${config:jellyfinDir}/bin/Debug/net8.0/jellyfin.dll",
|
||||
"args": [
|
||||
//"--nowebclient"
|
||||
"--webdir",
|
||||
"${config:jellyfinWebDir}/dist/"
|
||||
],
|
||||
"cwd": "${config:jellyfinDir}",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The `request` type is specified as `launch`, as this `launch.json` file will start the Jellyfin Server process. The `preLaunchTask` defines a task that will run before the Jellyfin Server starts. More on this later. It is important to set the `program` path to the Jellyin Server program and set the current working directory (`cwd`) to the working directory of the Jellyfin Server.
|
||||
The `args` option allows to specify arguments to be passed to the server, e.g. whether Jellyfin should start with the web-client or without it.
|
||||
|
||||
2. Create a `tasks.json` file inside your `.vscode` folder and specify a `build-and-copy` task that will run in `sequence` order. This tasks depends on multiple other tasks and all of those other tasks can be defined as simple `shell` tasks that run commands like the `cp` command to copy a file. The sequence to run those tasks in is given below. Please note that it might be necessary to adjust the examples for your specific setup and operating system.
|
||||
|
||||
The full file is shown here - Specific sections will be discussed in depth
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Paths and plugin name are configured in settings.json
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
// A chain task - build the plugin, then copy it to your
|
||||
// jellyfin server's plugin directory
|
||||
"label": "build-and-copy",
|
||||
"dependsOrder": "sequence",
|
||||
"dependsOn": ["build", "make-plugin-dir", "copy-dll"]
|
||||
},
|
||||
{
|
||||
// Build the plugin
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "shell",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/${config:pluginName}.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
// Ensure the plugin directory exists before trying to use it
|
||||
"label": "make-plugin-dir",
|
||||
"type": "shell",
|
||||
"command": "mkdir",
|
||||
"args": [
|
||||
"-Force",
|
||||
"-Path",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
{
|
||||
// Copy the plugin dll to the jellyfin plugin install path
|
||||
// This command copies every .dll from the build directory to the plugin dir
|
||||
// Usually, you probablly only need ${config:pluginName}.dll
|
||||
// But some plugins may bundle extra requirements
|
||||
"label": "copy-dll",
|
||||
"type": "shell",
|
||||
"command": "cp",
|
||||
"args": [
|
||||
"./${config:pluginName}/bin/Debug/net8.0/publish/*",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
1. The "build-and-copy" task which triggers all of the other tasks
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// A chain task - build the plugin, then copy it to your
|
||||
// jellyfin server's plugin directory
|
||||
"label": "build-and-copy",
|
||||
"dependsOrder": "sequence",
|
||||
"dependsOn": ["build", "make-plugin-dir", "copy-dll"]
|
||||
},
|
||||
```
|
||||
|
||||
2. A build task. This task builds the plugin without generating summary, but with full paths for file names enabled.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Build the plugin
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "shell",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/${config:pluginName}.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
```
|
||||
|
||||
3. A tasks which creates the necessary plugin directory and a sub-folder for the specific plugin. The plugin directory is located below the [data directory](https://jellyfin.org/docs/general/administration/configuration.html) of the Jellyfin Server. As an example, the following path can be used for the bookshelf plugin: `$HOME/.local/share/jellyfin/plugins/Bookshelf/`
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Ensure the plugin directory exists before trying to use it
|
||||
"label": "make-plugin-dir",
|
||||
"type": "shell",
|
||||
"command": "mkdir",
|
||||
"args": [
|
||||
"-Force",
|
||||
"-Path",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
4. A tasks which copies the plugin dll which has been built in step 2.1. The file is copied into it's specific plugin directory within the server's plugin directory.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Copy the plugin dll to the jellyfin plugin install path
|
||||
// This command copies every .dll from the build directory to the plugin dir
|
||||
// Usually, you probablly only need ${config:pluginName}.dll
|
||||
// But some plugins may bundle extra requirements
|
||||
"label": "copy-dll",
|
||||
"type": "shell",
|
||||
"command": "cp",
|
||||
"args": [
|
||||
"./${config:pluginName}/bin/Debug/net8.0/publish/*",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
## Licensing
|
||||
|
||||
Licensing is a complex topic. This repository features a GPLv3 license template that can be used to provide a good default license for your plugin. You may alter this if you like, but if you do a permissive license must be chosen.
|
||||
|
||||
Due to how plugins in Jellyfin work, when your plugin is compiled into a binary, it will link against the various Jellyfin binary NuGet packages. These packages are licensed under the GPLv3. Thus, due to the nature and restrictions of the GPL, the binary plugin you get will also be licensed under the GPLv3.
|
||||
|
||||
If you accept the default GPLv3 license from this template, all will be good. However if you choose a different license, please keep this fact in mind, as it might not always be obvious that an, e.g. MIT-licensed plugin would become GPLv3 when compiled.
|
||||
|
||||
Please note that this also means making "proprietary", source-unavailable, or otherwise "hidden" plugins for public consumption is not permitted. To build a Jellyfin plugin for distribution to others, it must be under the GPLv3 or a permissive open-source license that can be linked against the GPLv3.
|
||||
GPL-3.0, see [LICENSE](LICENSE).
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
# Summary
|
||||
|
||||
## What was built
|
||||
|
||||
`Jellyfin.Plugin.Herald`, a plugin for Jellyfin 10.11.x (built against 10.11.11, `net9.0`), started from `jellyfin/jellyfin-plugin-template`.
|
||||
|
||||
- **Notices**: data model with revisions and per-user acknowledgements, REST API under `/Herald` (pending notices and ack for users; CRUD, re-show and ack report for admins), an admin page in the dashboard, and a dependency-free client script that shows pending notices in jellyfin-web one at a time.
|
||||
- **Client injection**: registered with the File Transformation plugin by reflection at startup; a warning is logged when that plugin is missing. Manual fallbacks are documented.
|
||||
- **Watch-time stats**: playback start/progress/stop events are turned into daily per-user aggregates; `GET /Herald/Stats` and a sortable "Stats" tab show them; a daily scheduled task drops rows older than 90 days.
|
||||
- **Storage**: one SQLite database in Jellyfin's data directory, using the `Microsoft.Data.Sqlite` that the server ships. Versioned migrations, serialized writes.
|
||||
- **Project plumbing**: xUnit test project (64 tests), `build.yaml` for jprm, a Gitea Actions workflow (build, test, package; tags and releases automatically when the version changes), the plugin repository `manifest.json`, `README.md`, `DECISIONS.md`.
|
||||
|
||||
## What was verified, and how
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| `dotnet build -c Release` | Succeeds, 0 warnings, 0 errors (template analyzers kept, warnings as errors). |
|
||||
| `dotnet test -c Release` | 64 passed. Covers watch-time deltas (pause, seek, gaps, stale sessions, midnight incl. a non-UTC zone), pending-notice selection (revision bump, targeting, disabled), ack validation, the SQLite stores incl. concurrent writes and migrations, and the index.html transformer. |
|
||||
| `jprm plugin build` | Produces `artifacts/herald_1.0.0.0.zip` containing only `Jellyfin.Plugin.Herald.dll` and `meta.json`. `jprm repo add` accepted it and generated a manifest. |
|
||||
| Docker, `jellyfin/jellyfin:10.11.11` + File Transformation 3.0.3.0 (its 10.11.11 build) | The zip from jprm was unpacked into `plugins/Herald_1.0.0.0/`. Log: `Loaded plugin: Herald 1.0.0.0`, `Registered the Herald client script with File Transformation 3.0.3.0`, scheduled task registered, no `[ERR]` lines. `/Plugins` reports both plugins as `Active`. |
|
||||
| Injection | `GET /web/index.html` and `GET /web/` contain the `<script data-herald-client … src="../Herald/client.js">` tag; script chunks are untouched. |
|
||||
| Without File Transformation | Plugin still loads, the warning is logged, `index.html` is unchanged, `/Herald/client.js` still answers. |
|
||||
| API (curl, admin and non-admin token) | Create/read/update/delete/re-show, pending, ack, ack report and stats all answer as documented; non-admin gets `403` on admin routes, anonymous gets `401`; dismissing a must-accept notice gives `400`, an outdated revision `409`, a notice not addressed to the caller `404`. |
|
||||
| Config page (headless Chromium) | Page opens under Dashboard → Plugins → Herald; list, create form with user picker, edit prefill, enable toggle, responses view, re-show with confirmation, and the Stats tab with sorting all work; no console errors. |
|
||||
| Popup (headless Chromium, logged in as a normal user) | Must-accept notice shows only "Accept", Escape and outside click do nothing; next notice shows "Close" and Escape dismisses it; one `Pending` request after login and none on navigation; HTML and `javascript:` links in a notice are rendered as text. |
|
||||
| Stats end to end | A playback was reported through `/Sessions/Playing*` for a generated test video: 5 s + 5 s playing, 6 s paused, 4 s + 3 s playing with a seek in between. Stored: 17.15 s, 1 play. |
|
||||
|
||||
Two bugs were found and fixed through the container test: the transformer touched a JavaScript chunk that File Transformation also matches against the `index.html` pattern, which broke the login page, and jellyfin-web's `document.createElement` shim rejected the element-options form used by the admin page.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- Notices only appear in clients built on jellyfin-web. Native clients are not covered and cannot be from a plugin.
|
||||
- The popup was tested in Chromium against the default dark theme and NeutralFin, at desktop and phone size. The TV layout and real mobile wrappers were not tried.
|
||||
- The JavaScript Injector fallback and the manual `index.html` edit are documented but were not run.
|
||||
- File Transformation was tested in version 3.0.3.0 only, alone and together with MediaBar 3.0.2.0 and Jellyfin Enhanced 12.15.0.0. Its registration API is found by reflection, so a rename on their side turns into the logged warning, not a crash.
|
||||
- Stats were verified with simulated reports, not with a real player. The systematic inaccuracies are listed in the README.
|
||||
- The UI is English only.
|
||||
- Must-accept is a record of consent, not an access gate: nothing on the server is blocked for users who have not accepted.
|
||||
|
||||
## Environment notes
|
||||
|
||||
- No .NET SDK was installed, so the .NET 9 SDK (9.0.321) was installed with Microsoft's `dotnet-install.sh` into `~/.dotnet`. Use `export PATH=$HOME/.dotnet:$PATH DOTNET_ROOT=$HOME/.dotnet` to build, or remove that folder if you prefer a system package.
|
||||
- The Docker image `jellyfin/jellyfin:10.11.11` was pulled and is still present; the test container was removed.
|
||||
- `TASK.md` is left untracked.
|
||||
|
||||
## Next steps
|
||||
|
||||
- Try the popup on the themes and devices your users actually have.
|
||||
- Optional: start/end dates for notices, a history of earlier rounds in the responses view, translations.
|
||||
+19
-9
@@ -1,16 +1,26 @@
|
||||
---
|
||||
name: "Template"
|
||||
guid: "eb5d7894-8eef-4b36-aa6f-5d124e828ce1"
|
||||
version: "1.0.0.0"
|
||||
name: "Herald"
|
||||
guid: "006114bd-2c46-407b-8b31-57199a10fb1c"
|
||||
version: "1.1.0.0"
|
||||
# Jellyfin 10.11.x. Built against Jellyfin.Controller / Jellyfin.Model 10.11.11
|
||||
# (see Directory.Build.props). Plugins built for 10.11 do not load on 10.10 or 12.x.
|
||||
targetAbi: "10.11.0.0"
|
||||
framework: "net9.0"
|
||||
overview: "Short description about your plugin"
|
||||
overview: "One-time notices for your users and simple watch-time stats"
|
||||
description: >
|
||||
This is a longer description that can span more than one
|
||||
line and include details about your plugin.
|
||||
Admins write notices that pop up once per user in the web client, optionally
|
||||
requiring the user to accept them, and can see who responded. Also keeps an
|
||||
approximate per-user watch time for the last weeks.
|
||||
|
||||
Showing notices automatically needs the File Transformation plugin
|
||||
(https://github.com/IAmParadox27/jellyfin-plugin-file-transformation), which
|
||||
is not bundled. Without it the client script has to be added by hand, see the
|
||||
README. Microsoft.Data.Sqlite is used from the Jellyfin server itself and is
|
||||
not bundled either.
|
||||
category: "General"
|
||||
owner: "jellyfin"
|
||||
owner: "JoshiCodes"
|
||||
artifacts:
|
||||
- "Jellyfin.Plugin.Template.dll"
|
||||
- "Jellyfin.Plugin.Herald.dll"
|
||||
changelog: >
|
||||
changelog
|
||||
Must-accept notices can have a wait: the Accept button stays locked and
|
||||
counts down for a set number of seconds.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
[
|
||||
{
|
||||
"guid": "006114bd-2c46-407b-8b31-57199a10fb1c",
|
||||
"name": "Herald",
|
||||
"description": "Admins write notices that pop up once per user in the web client, optionally requiring the user to accept them, and can see who responded. Also keeps an approximate per-user watch time for the last weeks.\nShowing notices automatically needs the File Transformation plugin (https://github.com/IAmParadox27/jellyfin-plugin-file-transformation), which is not bundled. Without it the client script has to be added by hand, see the README. Microsoft.Data.Sqlite is used from the Jellyfin server itself and is not bundled either.\n",
|
||||
"overview": "One-time notices for your users and simple watch-time stats",
|
||||
"owner": "JoshiCodes",
|
||||
"category": "General",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.0.1.0",
|
||||
"changelog": "Notices now show up when other plugins (MediaBar, Home Screen Sections, ...) also change index.html through File Transformation. Herald has its own entry in the dashboard sidebar.\n",
|
||||
"targetAbi": "10.11.0.0",
|
||||
"sourceUrl": "https://git.joshicodes.de/JoshiCodes/jellyfin-herald/releases/download/v1.0.1.0/herald_1.0.1.0.zip",
|
||||
"checksum": "a65e32fbc536fa668a544739e24766a5",
|
||||
"timestamp": "2026-11-13T21:36:23Z"
|
||||
},
|
||||
{
|
||||
"version": "1.0.0.0",
|
||||
"changelog": "Initial release: notices with acknowledgement tracking, watch-time stats.\n",
|
||||
"targetAbi": "10.11.0.0",
|
||||
"sourceUrl": "https://git.joshicodes.de/JoshiCodes/jellyfin-herald/releases/download/v1.0.0.0/herald_1.0.0.0.zip",
|
||||
"checksum": "6bf1e0b971dc178c9b86d48a07d657d2",
|
||||
"timestamp": "2026-11-13T18:10:25Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user