feat(plugin): added basic plugin
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
**/bin/
|
||||
**/obj/
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Collections.Generic;
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// MovieNight plugin settings persisted by Jellyfin.
|
||||
/// </summary>
|
||||
public class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether integration calls are enabled.
|
||||
/// </summary>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the MovieNight backend base URL.
|
||||
/// </summary>
|
||||
public string BackendBaseUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the backend plugin token.
|
||||
/// </summary>
|
||||
public string ApiToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the periodic sync interval in minutes.
|
||||
/// </summary>
|
||||
public int SyncIntervalMinutes { get; set; } = 30;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether playback stop events are pushed to MovieNight.
|
||||
/// </summary>
|
||||
public bool EnablePlaybackEvents { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether periodic backend sync is enabled.
|
||||
/// </summary>
|
||||
public bool EnablePeriodicSync { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets enabled Jellyfin library ids. Empty means all libraries.
|
||||
/// </summary>
|
||||
public List<string> EnabledLibraryIds { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
const movieNightConfigPage = {
|
||||
pluginId: "42c72919-d6ff-4f62-bb8c-0fac39efafdb",
|
||||
|
||||
loadConfiguration(view) {
|
||||
Dashboard.showLoadingMsg();
|
||||
|
||||
return ApiClient.getPluginConfiguration(this.pluginId)
|
||||
.then((config) => {
|
||||
view.querySelector("#BackendBaseUrl").value =
|
||||
config.BackendBaseUrl || "";
|
||||
view.querySelector("#ApiToken").value = config.ApiToken || "";
|
||||
view.querySelector("#SyncIntervalMinutes").value =
|
||||
config.SyncIntervalMinutes || 30;
|
||||
view.querySelector("#Enabled").checked = config.Enabled || false;
|
||||
view.querySelector("#EnablePeriodicSync").checked =
|
||||
config.EnablePeriodicSync !== false;
|
||||
view.querySelector("#EnablePlaybackEvents").checked =
|
||||
config.EnablePlaybackEvents !== false;
|
||||
})
|
||||
.finally(() => {
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
},
|
||||
|
||||
saveConfiguration(view) {
|
||||
const form = view.querySelector("#MovieNightConfigForm");
|
||||
Dashboard.showLoadingMsg();
|
||||
|
||||
return ApiClient.getPluginConfiguration(this.pluginId)
|
||||
.then((config) => {
|
||||
config.BackendBaseUrl = form.querySelector("#BackendBaseUrl").value;
|
||||
config.ApiToken = form.querySelector("#ApiToken").value;
|
||||
config.SyncIntervalMinutes = parseInt(
|
||||
form.querySelector("#SyncIntervalMinutes").value || "30",
|
||||
10,
|
||||
);
|
||||
config.Enabled = form.querySelector("#Enabled").checked;
|
||||
config.EnablePeriodicSync =
|
||||
form.querySelector("#EnablePeriodicSync").checked;
|
||||
config.EnablePlaybackEvents =
|
||||
form.querySelector("#EnablePlaybackEvents").checked;
|
||||
|
||||
return ApiClient.updatePluginConfiguration(this.pluginId, config);
|
||||
})
|
||||
.then((result) => {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
})
|
||||
.finally(() => {
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
},
|
||||
|
||||
testConnection() {
|
||||
Dashboard.showLoadingMsg();
|
||||
|
||||
return ApiClient.ajax({
|
||||
type: "POST",
|
||||
url: ApiClient.getUrl("MovieNight/TestConnection"),
|
||||
})
|
||||
.then((result) => {
|
||||
Dashboard.alert((result && result.message) || "OK");
|
||||
})
|
||||
.catch(() => {
|
||||
Dashboard.alert("MovieNight connection test failed");
|
||||
})
|
||||
.finally(() => {
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default function (view) {
|
||||
movieNightConfigPage.loadConfiguration(view);
|
||||
|
||||
view
|
||||
.querySelector("#MovieNightConfigForm")
|
||||
.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
movieNightConfigPage.saveConfiguration(view);
|
||||
});
|
||||
|
||||
view.querySelector("#TestConnection").addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
movieNightConfigPage.testConnection();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>MovieNight</title>
|
||||
</head>
|
||||
<body>
|
||||
<div
|
||||
id="MovieNightConfigPage"
|
||||
data-role="page"
|
||||
class="page type-interior pluginConfigurationPage"
|
||||
data-controller="__plugin/MovieNight.js">
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<form id="MovieNightConfigForm">
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="BackendBaseUrl">Backend URL</label>
|
||||
<input is="emby-input" id="BackendBaseUrl" name="BackendBaseUrl" type="url" placeholder="http://localhost:8080" />
|
||||
</div>
|
||||
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="ApiToken">Plugin token</label>
|
||||
<input is="emby-input" id="ApiToken" name="ApiToken" type="password" autocomplete="new-password" />
|
||||
</div>
|
||||
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="SyncIntervalMinutes">Sync interval minutes</label>
|
||||
<input is="emby-input" id="SyncIntervalMinutes" name="SyncIntervalMinutes" type="number" min="1" max="1440" />
|
||||
</div>
|
||||
|
||||
<label class="checkboxContainer">
|
||||
<input id="Enabled" name="Enabled" type="checkbox" is="emby-checkbox" />
|
||||
<span>Enable MovieNight integration</span>
|
||||
</label>
|
||||
|
||||
<label class="checkboxContainer">
|
||||
<input id="EnablePeriodicSync" name="EnablePeriodicSync" type="checkbox" is="emby-checkbox" />
|
||||
<span>Enable periodic backend sync</span>
|
||||
</label>
|
||||
|
||||
<label class="checkboxContainer">
|
||||
<input id="EnablePlaybackEvents" name="EnablePlaybackEvents" type="checkbox" is="emby-checkbox" />
|
||||
<span>Send playback stop events</span>
|
||||
</label>
|
||||
|
||||
<div>
|
||||
<button is="emby-button" type="submit" class="raised button-submit block">
|
||||
<span>Save</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button is="emby-button" type="button" id="TestConnection" class="raised block">
|
||||
<span>Test connection</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.MovieNight.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Admin endpoints for the MovieNight plugin.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("MovieNight")]
|
||||
public class MovieNightController : ControllerBase
|
||||
{
|
||||
private readonly MovieNightBackendClient _backendClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovieNightController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="backendClient">Backend client.</param>
|
||||
public MovieNightController(MovieNightBackendClient backendClient)
|
||||
{
|
||||
_backendClient = backendClient;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns plugin status.
|
||||
/// </summary>
|
||||
/// <returns>Status response.</returns>
|
||||
[HttpGet("Status")]
|
||||
public ActionResult<MovieNightPluginStatus> GetStatus()
|
||||
{
|
||||
var configuration = Plugin.Instance?.Configuration;
|
||||
return new MovieNightPluginStatus(
|
||||
Enabled: configuration?.Enabled ?? false,
|
||||
BackendBaseUrl: configuration?.BackendBaseUrl ?? string.Empty,
|
||||
PeriodicSyncEnabled: configuration?.EnablePeriodicSync ?? false,
|
||||
PlaybackEventsEnabled: configuration?.EnablePlaybackEvents ?? false,
|
||||
SyncIntervalMinutes: configuration?.SyncIntervalMinutes ?? 30);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tests backend connectivity.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Connection result.</returns>
|
||||
[HttpPost("TestConnection")]
|
||||
public async Task<ActionResult<MovieNightConnectionResult>> TestConnection(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _backendClient.TestConnectionAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Triggers backend sync.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Backend response.</returns>
|
||||
[HttpPost("Sync")]
|
||||
public async Task<ActionResult<string>> Sync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _backendClient.TriggerSyncAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets backend sync state.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Backend response.</returns>
|
||||
[HttpGet("SyncState")]
|
||||
public async Task<ActionResult<string>> SyncState(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _backendClient.GetSyncStateAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MovieNight plugin status response.
|
||||
/// </summary>
|
||||
/// <param name="Enabled">Whether integration is enabled.</param>
|
||||
/// <param name="BackendBaseUrl">Backend base URL.</param>
|
||||
/// <param name="PeriodicSyncEnabled">Whether periodic sync is enabled.</param>
|
||||
/// <param name="PlaybackEventsEnabled">Whether playback events are enabled.</param>
|
||||
/// <param name="SyncIntervalMinutes">Sync interval in minutes.</param>
|
||||
public sealed record MovieNightPluginStatus(
|
||||
bool Enabled,
|
||||
string BackendBaseUrl,
|
||||
bool PeriodicSyncEnabled,
|
||||
bool PlaybackEventsEnabled,
|
||||
int SyncIntervalMinutes);
|
||||
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<RootNamespace>Jellyfin.Plugin.MovieNight</RootNamespace>
|
||||
<AssemblyName>Jellyfin.Plugin.MovieNight</AssemblyName>
|
||||
<Version>1.0.0.1</Version>
|
||||
<PackageLicenseExpression>GPL-3.0-or-later</PackageLicenseExpression>
|
||||
<Nullable>enable</Nullable>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
<PackageReference Include="Jellyfin.Common" Version="10.11.5">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<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>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Configuration\configPage.html" />
|
||||
<None Remove="Configuration\config.js" />
|
||||
<EmbeddedResource Include="Configuration\configPage.html" />
|
||||
<EmbeddedResource Include="Configuration\config.js" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Jellyfin.Plugin.MovieNight.Configuration;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Plugins;
|
||||
using MediaBrowser.Model.Plugins;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight;
|
||||
|
||||
/// <summary>
|
||||
/// MovieNight Jellyfin plugin.
|
||||
/// </summary>
|
||||
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="Plugin"/> class.
|
||||
/// </summary>
|
||||
/// <param name="applicationPaths">Application paths.</param>
|
||||
/// <param name="xmlSerializer">XML serializer.</param>
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
|
||||
: base(applicationPaths, xmlSerializer)
|
||||
{
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Name => "MovieNight";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Guid Id => Guid.Parse("42c72919-d6ff-4f62-bb8c-0fac39efafdb");
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Description => "Bridges Jellyfin playback and sync signals to the MovieNight backend.";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current plugin instance.
|
||||
/// </summary>
|
||||
public static Plugin? Instance { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<PluginPageInfo> GetPages()
|
||||
{
|
||||
return
|
||||
[
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = Name,
|
||||
EmbeddedResourcePath = string.Format(
|
||||
CultureInfo.InvariantCulture,
|
||||
"{0}.Configuration.configPage.html",
|
||||
GetType().Namespace)
|
||||
},
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = Name + ".js",
|
||||
EmbeddedResourcePath = string.Format(
|
||||
CultureInfo.InvariantCulture,
|
||||
"{0}.Configuration.config.js",
|
||||
GetType().Namespace)
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Jellyfin.Plugin.MovieNight.Services;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight;
|
||||
|
||||
/// <summary>
|
||||
/// Registers MovieNight services with Jellyfin.
|
||||
/// </summary>
|
||||
public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
|
||||
{
|
||||
serviceCollection.AddSingleton<MovieNightBackendClient>();
|
||||
serviceCollection.AddHostedService<MovieNightPeriodicSyncService>();
|
||||
serviceCollection.AddHostedService<MovieNightPlaybackEventService>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Thin HTTP client for the MovieNight backend.
|
||||
/// </summary>
|
||||
public class MovieNightBackendClient
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
private readonly ILogger<MovieNightBackendClient> _logger;
|
||||
private readonly HttpClient _httpClient;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovieNightBackendClient"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger.</param>
|
||||
public MovieNightBackendClient(ILogger<MovieNightBackendClient> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_httpClient = new HttpClient
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(20)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calls backend health.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Connection result.</returns>
|
||||
public async Task<MovieNightConnectionResult> TestConnectionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var payload = new MovieNightEventPayload(
|
||||
EventId: $"plugin-test:{Guid.NewGuid():N}",
|
||||
EventType: "playback.stopped",
|
||||
OccurredAt: DateTimeOffset.UtcNow,
|
||||
JellyfinUserId: "movienight-plugin-test-user",
|
||||
ItemId: "movienight-plugin-test-item",
|
||||
PayloadVersion: 1,
|
||||
Payload: new Dictionary<string, object?>
|
||||
{
|
||||
["source"] = "config-test"
|
||||
});
|
||||
var request = CreateEventRequest(payload);
|
||||
if (request is null)
|
||||
{
|
||||
return MovieNightConnectionResult.Failed("Plugin is not configured.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
return response.IsSuccessStatusCode
|
||||
? MovieNightConnectionResult.Ok()
|
||||
: MovieNightConnectionResult.Failed($"Backend event endpoint returned {(int)response.StatusCode}.");
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "MovieNight connection test failed");
|
||||
return MovieNightConnectionResult.Failed(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Triggers the current backend Jellyfin sync endpoint.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Backend response body.</returns>
|
||||
public async Task<string> TriggerSyncAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var request = CreateRequest(HttpMethod.Post, "/api/integrations/jellyfin/sync");
|
||||
if (request is null)
|
||||
{
|
||||
return "Plugin is not configured.";
|
||||
}
|
||||
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads backend sync state.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Backend response body.</returns>
|
||||
public async Task<string> GetSyncStateAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var request = CreateRequest(HttpMethod.Get, "/api/integrations/jellyfin/sync-state");
|
||||
if (request is null)
|
||||
{
|
||||
return "Plugin is not configured.";
|
||||
}
|
||||
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pushes an event payload to the backend event endpoint.
|
||||
/// </summary>
|
||||
/// <param name="payload">Event payload.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task PushEventAsync(MovieNightEventPayload payload, CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 1; attempt <= 3; attempt++)
|
||||
{
|
||||
var request = CreateEventRequest(payload);
|
||||
if (request is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if ((int)response.StatusCode == 401)
|
||||
{
|
||||
_logger.LogWarning("MovieNight event push was rejected with 401 Unauthorized");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogDebug("MovieNight event push returned status {StatusCode}", response.StatusCode);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
||||
{
|
||||
_logger.LogDebug(ex, "MovieNight event push attempt {Attempt} failed", attempt);
|
||||
}
|
||||
|
||||
if (attempt < 3)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(attempt * 2), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpRequestMessage? CreateEventRequest(MovieNightEventPayload payload)
|
||||
{
|
||||
var request = CreateRequest(HttpMethod.Post, "/api/integrations/jellyfin/events");
|
||||
if (request is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
request.Content = JsonContent.Create(payload, options: JsonOptions);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static string? GetBaseUrl()
|
||||
{
|
||||
var value = Plugin.Instance?.Configuration.BackendBaseUrl?.Trim();
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value.TrimEnd('/');
|
||||
}
|
||||
|
||||
private static bool IsEnabled()
|
||||
{
|
||||
var configuration = Plugin.Instance?.Configuration;
|
||||
return configuration is { Enabled: true } && !string.IsNullOrWhiteSpace(configuration.BackendBaseUrl);
|
||||
}
|
||||
|
||||
private static HttpRequestMessage? CreateRequest(HttpMethod method, string path)
|
||||
{
|
||||
if (!IsEnabled())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var baseUrl = GetBaseUrl();
|
||||
if (baseUrl is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var request = new HttpRequestMessage(method, new Uri(baseUrl + path));
|
||||
var token = Plugin.Instance?.Configuration.ApiToken;
|
||||
if (!string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
request.Headers.Add("X-MovieNight-Plugin-Token", token);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Backend connection result.
|
||||
/// </summary>
|
||||
/// <param name="Success">Whether the call succeeded.</param>
|
||||
/// <param name="Message">Result message.</param>
|
||||
public sealed record MovieNightConnectionResult(bool Success, string Message)
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a successful result.
|
||||
/// </summary>
|
||||
/// <returns>Connection result.</returns>
|
||||
public static MovieNightConnectionResult Ok() => new(true, "OK");
|
||||
|
||||
/// <summary>
|
||||
/// Creates a failed result.
|
||||
/// </summary>
|
||||
/// <param name="message">Failure message.</param>
|
||||
/// <returns>Connection result.</returns>
|
||||
public static MovieNightConnectionResult Failed(string message) => new(false, message);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Event payload sent to MovieNight.
|
||||
/// </summary>
|
||||
/// <param name="EventId">Idempotency key.</param>
|
||||
/// <param name="EventType">Event type.</param>
|
||||
/// <param name="OccurredAt">Event timestamp.</param>
|
||||
/// <param name="JellyfinUserId">Jellyfin user id.</param>
|
||||
/// <param name="ItemId">Jellyfin item id.</param>
|
||||
/// <param name="PayloadVersion">Payload version.</param>
|
||||
/// <param name="Payload">Extra event data.</param>
|
||||
public sealed record MovieNightEventPayload(
|
||||
[property: JsonPropertyName("event_id")]
|
||||
string EventId,
|
||||
[property: JsonPropertyName("event_type")]
|
||||
string EventType,
|
||||
[property: JsonPropertyName("occurred_at")]
|
||||
DateTimeOffset OccurredAt,
|
||||
[property: JsonPropertyName("jellyfin_user_id")]
|
||||
string JellyfinUserId,
|
||||
[property: JsonPropertyName("item_id")]
|
||||
string ItemId,
|
||||
[property: JsonPropertyName("payload_version")]
|
||||
int PayloadVersion,
|
||||
[property: JsonPropertyName("payload")]
|
||||
IReadOnlyDictionary<string, object?> Payload);
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Periodically asks MovieNight to run its current Jellyfin sync.
|
||||
/// </summary>
|
||||
public sealed class MovieNightPeriodicSyncService : BackgroundService
|
||||
{
|
||||
private readonly MovieNightBackendClient _backendClient;
|
||||
private readonly ILogger<MovieNightPeriodicSyncService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovieNightPeriodicSyncService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="backendClient">Backend client.</param>
|
||||
/// <param name="logger">Logger.</param>
|
||||
public MovieNightPeriodicSyncService(
|
||||
MovieNightBackendClient backendClient,
|
||||
ILogger<MovieNightPeriodicSyncService> logger)
|
||||
{
|
||||
_backendClient = backendClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
var delay = GetDelay();
|
||||
try
|
||||
{
|
||||
await Task.Delay(delay, stoppingToken).ConfigureAwait(false);
|
||||
if (!ShouldRun())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await _backendClient.TriggerSyncAsync(stoppingToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "MovieNight periodic sync failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ShouldRun()
|
||||
{
|
||||
var configuration = Plugin.Instance?.Configuration;
|
||||
return configuration is { Enabled: true, EnablePeriodicSync: true };
|
||||
}
|
||||
|
||||
private static TimeSpan GetDelay()
|
||||
{
|
||||
var minutes = Plugin.Instance?.Configuration.SyncIntervalMinutes ?? 30;
|
||||
return TimeSpan.FromMinutes(Math.Clamp(minutes, 1, 1440));
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.MovieNight.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to Jellyfin playback events and forwards thin payloads.
|
||||
/// </summary>
|
||||
public sealed class MovieNightPlaybackEventService : IHostedService
|
||||
{
|
||||
private readonly ISessionManager _sessionManager;
|
||||
private readonly MovieNightBackendClient _backendClient;
|
||||
private readonly ILogger<MovieNightPlaybackEventService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MovieNightPlaybackEventService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="sessionManager">Jellyfin session manager.</param>
|
||||
/// <param name="backendClient">Backend client.</param>
|
||||
/// <param name="logger">Logger.</param>
|
||||
public MovieNightPlaybackEventService(
|
||||
ISessionManager sessionManager,
|
||||
MovieNightBackendClient backendClient,
|
||||
ILogger<MovieNightPlaybackEventService> logger)
|
||||
{
|
||||
_sessionManager = sessionManager;
|
||||
_backendClient = backendClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_sessionManager.PlaybackStopped += OnPlaybackStopped;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_sessionManager.PlaybackStopped -= OnPlaybackStopped;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnPlaybackStopped(object? sender, PlaybackStopEventArgs e)
|
||||
{
|
||||
if (Plugin.Instance?.Configuration is not { Enabled: true, EnablePlaybackEvents: true })
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!e.PlayedToCompletion)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var userId = e.Users?.FirstOrDefault()?.Id.ToString("N");
|
||||
var itemId = e.Item?.Id.ToString("N");
|
||||
if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(itemId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var occurredAt = DateTimeOffset.UtcNow;
|
||||
var eventId = string.IsNullOrWhiteSpace(e.PlaySessionId)
|
||||
? $"playback-stopped:{userId}:{itemId}:{occurredAt.ToUnixTimeMilliseconds()}"
|
||||
: $"playback-stopped:{userId}:{itemId}:{e.PlaySessionId}";
|
||||
|
||||
var payload = new MovieNightEventPayload(
|
||||
EventId: eventId,
|
||||
EventType: "playback.stopped",
|
||||
OccurredAt: occurredAt,
|
||||
JellyfinUserId: userId,
|
||||
ItemId: itemId,
|
||||
PayloadVersion: 1,
|
||||
Payload: new Dictionary<string, object?>
|
||||
{
|
||||
["itemName"] = e.Item?.Name,
|
||||
["playSessionId"] = e.PlaySessionId,
|
||||
["positionTicks"] = e.PlaybackPositionTicks,
|
||||
["playedToCompletion"] = e.PlayedToCompletion
|
||||
});
|
||||
|
||||
_ = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await _backendClient.PushEventAsync(payload, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "MovieNight playback event push failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# MovieNight Jellyfin Plugin
|
||||
|
||||
Thin Jellyfin server plugin for bridging Jellyfin playback/sync signals to the MovieNight backend.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
cd plugins/jellyfin/Jellyfin.Plugin.MovieNight
|
||||
dotnet publish -c Release
|
||||
```
|
||||
|
||||
Install the published `net9.0` plugin files into the Jellyfin data directory under `plugins/MovieNight/`, then restart Jellyfin. This build targets Jellyfin `10.11.x`.
|
||||
|
||||
## Backend Contract Used
|
||||
|
||||
Current implemented calls:
|
||||
|
||||
- `POST /api/integrations/jellyfin/sync`
|
||||
- `GET /api/integrations/jellyfin/sync-state`
|
||||
- `POST /api/integrations/jellyfin/events`
|
||||
|
||||
Event requests use JSON with:
|
||||
|
||||
- `event_id`
|
||||
- `event_type`
|
||||
- `occurred_at`
|
||||
- `jellyfin_user_id`
|
||||
- `item_id`
|
||||
- `payload_version`
|
||||
- `payload`
|
||||
|
||||
The plugin sends `X-MovieNight-Plugin-Token` when configured. Completed Jellyfin playback stop events are sent as `playback.stopped`. Transient event push failures are retried three times with the same `event_id`.
|
||||
|
||||
The config page test action posts a small synthetic event to `/api/integrations/jellyfin/events` and treats `200` as success and `401` as token/config failure.
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: "MovieNight"
|
||||
guid: "42c72919-d6ff-4f62-bb8c-0fac39efafdb"
|
||||
version: 2
|
||||
targetAbi: "10.11.0.0"
|
||||
framework: net9.0
|
||||
owner: "movienight"
|
||||
overview: "Bridge Jellyfin events and sync triggers to MovieNight"
|
||||
description: "Thin Jellyfin plugin for MovieNight backend integration"
|
||||
category: "General"
|
||||
artifacts:
|
||||
- "Jellyfin.Plugin.MovieNight.dll"
|
||||
changelog: |-
|
||||
- Initial plugin implementation.
|
||||
Reference in New Issue
Block a user