docs: add README, decisions and summary

This commit is contained in:
2026-11-13 18:10:41 +01:00
parent dba6a8ecef
commit 8618ee2573
3 changed files with 247 additions and 370 deletions
+55
View File
@@ -0,0 +1,55 @@
# 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.
- 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`.
- 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 `^index\.html$`. File Transformation treats patterns as regular expressions, and the unanchored `index.html` also matched the script chunk `session-login-index-html.<hash>.chunk.js`, which broke the login page. Found in the container test.
- The transformer leaves anything without a `</body>` alone, as a second line of defence against touching non-HTML files.
- 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.
## 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.
+137 -366
View File
@@ -1,425 +1,196 @@
# 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. Host the plugin zip and a `manifest.json` somewhere your server can reach (see [Hosting your own repository](#hosting-your-own-repository)).
2. In Jellyfin: **Dashboard → Plugins → Manage Repositories → New Repository**, enter the URL of your `manifest.json`.
3. 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 1. Take `herald_<version>.zip` from a release, or build it yourself (see [Building](#building)).
dotnet new -i /path/to/templatefolder 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`.
The settings page is under **Dashboard → Plugins → Herald**.
## Getting the popup into the web client
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.
### File Transformation (recommended)
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.
The log tells you which case you are in:
```
Registered the Herald client script with File Transformation 3.0.3.0
``` ```
- Run this command then skip to step 4 or, if it is missing:
```shell ```
dotnet new Jellyfin-plugin -name MyPlugin The File Transformation plugin is not installed, so the Herald client script is not injected ...
``` ```
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. File Transformation releases are tied to exact Jellyfin versions, so pick the build that matches your server.
## 1. Initialize Your Project ### Fallback: JavaScript Injector
Make a new dotnet standard project with the following command, it will make a directory for itself. With the [JavaScript Injector](https://github.com/n00bcodr/Jellyfin-JavaScript-Injector) plugin, add a script with this content and enable it:
```shell ```js
dotnet new classlib -f net9.0 -n MyJellyfinPlugin (function () {
var script = document.createElement('script');
script.src = '../Herald/client.js';
script.defer = true;
document.head.appendChild(script);
})();
``` ```
Now add the Jellyfin shared libraries. ### Fallback: edit index.html
```shell 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):
dotnet add package Jellyfin.Model
dotnet add package Jellyfin.Controller ```html
<script defer src="../Herald/client.js"></script>
``` ```
You have an autogenerated Class1.cs file. You won't be needing this, so go ahead and delete it. This is overwritten by every Jellyfin update.
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. 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.
Skipping this step will prevent your plugin from registering correctly.
```xml ## Using it
<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>
```
Note: Ensure the package reference version matches the install version of jellyfin server, otherwise the plugin will show as NotSupported. **Notices tab**
## 2. Set Up the Basics - *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).
- 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.
There are a few mandatory classes you'll need for a plugin so we need to make them. **What users see**
### PluginConfiguration 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. The script asks for new notices after login, after a user switch, and then every 10 minutes while the tab is visible.
Create a folder named "Configuration", and a PluginConfiguration.cs file inside. **Stats tab**
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` 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.
It should look something like the following: ## API
```csharp 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.
using MediaBrowser.Model.Plugins;
namespace MyJellyfinPlugin.Configuration; | Method | Route | Access | Purpose |
class PluginConfiguration : BasePluginConfiguration | --- | --- | --- | --- |
| `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`, `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,
"Enabled": true,
"Target": { "AllUsers": false, "UserIds": ["21b3bac6acfe496bbca02a21c21e36d4"] },
"Revision": 2,
"CreatedAt": "2026-11-13T16:57:12.5166578Z",
"UpdatedAt": "2026-11-13T16:57:12.9794785Z"
} }
``` ```
### Plugin ## How the stats are calculated
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>` Clients report to the server when playback starts, every few seconds while it runs, and when it stops. Herald listens to those reports:
It should look something like the following: - 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.
```csharp Where the numbers are off:
using MediaBrowser.Common.Plugins;
using MyJellyfinPlugin.Configuration;
namespace MyJellyfinPlugin; - **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.
class Plugin : BasePlugin<PluginConfiguration> ## 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
``` ```
Note: If you called your PluginConfiguration class something different, you need to put that between the <> Package with [jprm](https://github.com/oddstr13/jellyfin-plugin-repository-manager):
### Implement Required Properties ```sh
pip install jprm
The Plugin class needs a few properties implemented before it can work correctly. mkdir -p artifacts
jprm plugin build . --output artifacts
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.
```csharp
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer){}
public override string Name => throw new System.NotImplementedException();
public override Guid Id => Guid.Parse("");
``` ```
## 3. Customize Plugin Information 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`.
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 Pushing a tag such as `v1.0.0` runs the GitHub Actions workflow, which builds, tests, packages and attaches the zip to the release of that tag.
- **Windows Users**: you can use the Powershell command `New-Guid`, `[guid]::NewGuid()` or the Visual Studio GUID generator ## Hosting your own repository
- **Linux and OS X Users**: you can use the Powershell Core command `New-Guid` or this command from your shell of choice: `manifest.json` in this repository is a sample. Replace `OWNER/REPO`, the checksum (MD5 of the zip) and the timestamp, or let jprm write it:
```shell ```sh
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}' jprm repo init ./repo
jprm repo add --plugin-url https://github.com/OWNER/REPO/releases/download/v1.0.0/herald_1.0.0.0.zip ./repo artifacts/herald_1.0.0.0.zip
``` ```
or Serve the resulting `manifest.json` over HTTP(S) and add its URL in Jellyfin as described above.
```shell ## License
uuidgen
```
- Place that guid inside the `Guid.Parse("")` quotes to define your plugin's ID. GPL-3.0, see [LICENSE](LICENSE).
## 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
```
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.
### 6.a Set Up Debugging on Visual Studio
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.
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'
From now on, everytime you click on start from Visual Studio, it will start Jellyfin attached to the debugger!
The only thing left to do is to compile the project as it is specified a few lines above and you are done.
### 6.b Automate the Setup on Visual Studio Code
Visual Studio Code allows developers to automate the process of starting all necessary dependencies to start debugging the plugin. This guide assumes the reader is familiar with the [documentation on debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) and has read the documentation in this file. It is assumed that the Jellyfin Server has already been compiled once. However, should one desire to automatically compile the server before the start of the debugging session, this can be easily implemented, but is not further discussed here.
A full example, which aims to be portable may be found in this repo's `.vscode` folder.
This example expects you to clone `jellyfin`, `jellyfin-web` and `jellyfin-plugin-template` under the same parent directory, though you can customize this in `settings.json`
1. Create a `settings.json` file inside your `.vscode` folder, to specify common options specific to your local setup.
```jsonc
{
// jellyfinDir : The directory of the cloned jellyfin server project
// This needs to be built once before it can be used
"jellyfinDir" : "${workspaceFolder}/../jellyfin/Jellyfin.Server",
// jellyfinWebDir : The directory of the cloned jellyfin-web project
// This needs to be built once before it can be used
"jellyfinWebDir" : "${workspaceFolder}/../jellyfin-web",
// jellyfinDataDir : the root data directory for a running jellyfin instance
// This is where jellyfin stores its configs, plugins, metadata etc
// This is platform specific by default, but on Windows defaults to
// ${env:LOCALAPPDATA}/jellyfin
"jellyfinDataDir" : "${env:LOCALAPPDATA}/jellyfin",
// The name of the plugin
"pluginName" : "Jellyfin.Plugin.Template",
}
```
1. To automate the launch process, create a new `launch.json` file for C# projects inside the `.vscode` folder. The example below shows only the relevant parts of the file. Adjustments to your specific setup and operating system may be required.
```jsonc
{
// Paths and plugin names are configured in settings.json
"version": "0.2.0",
"configurations": [
{
"type": "coreclr",
"name": "Launch",
"request": "launch",
"preLaunchTask": "build-and-copy",
"program": "${config:jellyfinDir}/bin/Debug/net8.0/jellyfin.dll",
"args": [
//"--nowebclient"
"--webdir",
"${config:jellyfinWebDir}/dist/"
],
"cwd": "${config:jellyfinDir}",
}
]
}
```
The `request` type is specified as `launch`, as this `launch.json` file will start the Jellyfin Server process. The `preLaunchTask` defines a task that will run before the Jellyfin Server starts. More on this later. It is important to set the `program` path to the Jellyin Server program and set the current working directory (`cwd`) to the working directory of the Jellyfin Server.
The `args` option allows to specify arguments to be passed to the server, e.g. whether Jellyfin should start with the web-client or without it.
2. Create a `tasks.json` file inside your `.vscode` folder and specify a `build-and-copy` task that will run in `sequence` order. This tasks depends on multiple other tasks and all of those other tasks can be defined as simple `shell` tasks that run commands like the `cp` command to copy a file. The sequence to run those tasks in is given below. Please note that it might be necessary to adjust the examples for your specific setup and operating system.
The full file is shown here - Specific sections will be discussed in depth
```jsonc
{
// Paths and plugin name are configured in settings.json
"version": "2.0.0",
"tasks": [
{
// A chain task - build the plugin, then copy it to your
// jellyfin server's plugin directory
"label": "build-and-copy",
"dependsOrder": "sequence",
"dependsOn": ["build", "make-plugin-dir", "copy-dll"]
},
{
// Build the plugin
"label": "build",
"command": "dotnet",
"type": "shell",
"args": [
"publish",
"${workspaceFolder}/${config:pluginName}.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
{
// Ensure the plugin directory exists before trying to use it
"label": "make-plugin-dir",
"type": "shell",
"command": "mkdir",
"args": [
"-Force",
"-Path",
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
]
},
{
// Copy the plugin dll to the jellyfin plugin install path
// This command copies every .dll from the build directory to the plugin dir
// Usually, you probablly only need ${config:pluginName}.dll
// But some plugins may bundle extra requirements
"label": "copy-dll",
"type": "shell",
"command": "cp",
"args": [
"./${config:pluginName}/bin/Debug/net8.0/publish/*",
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
]
},
]
}
```
1. The "build-and-copy" task which triggers all of the other tasks
```jsonc
{
// A chain task - build the plugin, then copy it to your
// jellyfin server's plugin directory
"label": "build-and-copy",
"dependsOrder": "sequence",
"dependsOn": ["build", "make-plugin-dir", "copy-dll"]
},
```
2. A build task. This task builds the plugin without generating summary, but with full paths for file names enabled.
```jsonc
{
// Build the plugin
"label": "build",
"command": "dotnet",
"type": "shell",
"args": [
"publish",
"${workspaceFolder}/${config:pluginName}.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
},
```
3. A tasks which creates the necessary plugin directory and a sub-folder for the specific plugin. The plugin directory is located below the [data directory](https://jellyfin.org/docs/general/administration/configuration.html) of the Jellyfin Server. As an example, the following path can be used for the bookshelf plugin: `$HOME/.local/share/jellyfin/plugins/Bookshelf/`
```jsonc
{
// Ensure the plugin directory exists before trying to use it
"label": "make-plugin-dir",
"type": "shell",
"command": "mkdir",
"args": [
"-Force",
"-Path",
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
]
},
```
4. A tasks which copies the plugin dll which has been built in step 2.1. The file is copied into it's specific plugin directory within the server's plugin directory.
```jsonc
{
// Copy the plugin dll to the jellyfin plugin install path
// This command copies every .dll from the build directory to the plugin dir
// Usually, you probablly only need ${config:pluginName}.dll
// But some plugins may bundle extra requirements
"label": "copy-dll",
"type": "shell",
"command": "cp",
"args": [
"./${config:pluginName}/bin/Debug/net8.0/publish/*",
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
]
},
```
## Licensing
Licensing is a complex topic. This repository features a GPLv3 license template that can be used to provide a good default license for your plugin. You may alter this if you like, but if you do a permissive license must be chosen.
Due to how plugins in Jellyfin work, when your plugin is compiled into a binary, it will link against the various Jellyfin binary NuGet packages. These packages are licensed under the GPLv3. Thus, due to the nature and restrictions of the GPL, the binary plugin you get will also be licensed under the GPLv3.
If you accept the default GPLv3 license from this template, all will be good. However if you choose a different license, please keep this fact in mind, as it might not always be obvious that an, e.g. MIT-licensed plugin would become GPLv3 when compiled.
Please note that this also means making "proprietary", source-unavailable, or otherwise "hidden" plugins for public consumption is not permitted. To build a Jellyfin plugin for distribution to others, it must be under the GPLv3 or a permissive open-source license that can be linked against the GPLv3.
+51
View File
@@ -0,0 +1,51 @@
# 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 (56 tests), `build.yaml` for jprm, a GitHub Actions workflow (build, test, package, attach zip to the release on tag push), a sample `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` | 56 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 unanchored File Transformation pattern also matched a JavaScript chunk and 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 against the default dark theme in Chromium. Other themes, 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. 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.
- The GitHub workflow has not run; there is no remote. The repository is local with commits on `main`.
- 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
- Put the repository on a remote, replace `OWNER/REPO` in `manifest.json`, push a `v1.0.0` tag and check the release workflow.
- 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.