Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
!Go/
!Jellyfin/frontend/
!shared/SmartSearch/
!shared/LiveTv/RecordingOwnerTags.cs
!shared/PosterBadges/flags/
!shared/WatchParty/invite.html
!shared/WatchParty/preview.png
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/moonbase-go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ name: Moonbase Go
on:
push:
branches: [master]
paths: ['Go/**', 'shared/SmartSearch/**', 'shared/Seasonal/seasonal-holidays.json', '.github/workflows/moonbase-go.yml']
paths: ['Go/**', 'shared/SmartSearch/**', 'shared/LiveTv/RecordingOwnerTags.cs', 'shared/Seasonal/seasonal-holidays.json', '.github/workflows/moonbase-go.yml']
pull_request:
branches: [master]
paths: ['Go/**', 'shared/SmartSearch/**', 'shared/Seasonal/seasonal-holidays.json', '.github/workflows/moonbase-go.yml']
paths: ['Go/**', 'shared/SmartSearch/**', 'shared/LiveTv/RecordingOwnerTags.cs', 'shared/Seasonal/seasonal-holidays.json', '.github/workflows/moonbase-go.yml']

permissions:
contents: read
Expand Down
59 changes: 59 additions & 0 deletions Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsRequests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,63 @@ public class SuggestedShowingBody

public SuggestedShowing? Showing { get; set; }
}

[Route("/Moonfin/LiveTv/Owners/Record", "POST")]
[Authenticated]
public class RecordOwnerRequest : IReturn<object>, IRequiresRequestStream
{
public System.IO.Stream RequestStream { get; set; } = null!;
}

[Route("/Moonfin/LiveTv/Owners/RecordSeries", "POST")]
[Authenticated]
public class RecordSeriesOwnerRequest : IReturn<object>, IRequiresRequestStream
{
public System.IO.Stream RequestStream { get; set; } = null!;
}

[Route("/Moonfin/LiveTv/Owners/Claim", "POST")]
[Authenticated]
public class ClaimOwnerRequest : IReturn<object>, IRequiresRequestStream
{
public System.IO.Stream RequestStream { get; set; } = null!;
}

[Route("/Moonfin/LiveTv/Owners/Lookup", "POST")]
[Authenticated]
public class LookupOwnersRequest : IReturn<object>, IRequiresRequestStream
{
public System.IO.Stream RequestStream { get; set; } = null!;
}

[Route("/Moonfin/LiveTv/Owners/Mine", "GET")]
[Authenticated]
public class GetMyOwnedRequest : IReturn<object> { }

/// <summary>Body for recording a program, or its series, as its owner.</summary>
public class RecordOwnerBody
{
public string? ProgramId { get; set; }

public System.Collections.Generic.Dictionary<string, System.Text.Json.JsonElement>? Settings { get; set; }
}

/// <summary>Body for claiming an existing timer, series rule or recording.</summary>
public class ClaimOwnerBody
{
/// <summary>timer, series or item.</summary>
public string? Kind { get; set; }

public string? Id { get; set; }
}

/// <summary>Body for looking owners up.</summary>
public class LookupOwnersBody
{
public System.Collections.Generic.List<string>? TimerIds { get; set; }

public System.Collections.Generic.List<string>? SeriesTimerIds { get; set; }

public System.Collections.Generic.List<string>? ItemIds { get; set; }
}
}
155 changes: 155 additions & 0 deletions Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ public async Task<object> Post(RequestCompleteShowingRequest request)
state = IncompleteRecordingRules.DisplayState(showing),
scheduledStart = showing.ScheduledStart,
channelName = showing.ScheduledChannelName,
otherOwners = OwnerList(service.OtherOwners(showing, user.Id, OwnersEnabled())),
});
}

Expand Down Expand Up @@ -181,6 +182,160 @@ public async Task<object> Post(SaveIncompleteRecordingSettingsRequest request)
return Json(IncompleteRecordingConfig.Read());
}

// ---- Recording owners (My Recordings) ----

private static bool OwnersEnabled() => Plugin.Instance?.Configuration?.LiveTvRecordingOwners ?? true;

private object OwnersNotFound() => Json(404, new { error = "Recording owners are not available" });

private static object[] OwnerList(System.Collections.Generic.IEnumerable<OwnerInfo> owners) =>
owners.Select(o => (object)new { userId = o.UserId.ToString("N"), name = o.Name, imageTag = o.ImageTag }).ToArray();

private static bool ProgramVisible(string programId, Guid userId)
{
var host = PluginServices.RecordingHost;
var program = host?.GetProgram(programId);
return program != null && host!.IsVisibleTo(program.ItemId, userId);
}

private object OwnershipResult(OwnershipOutcome outcome) =>
Json(new { id = outcome.Id, owners = OwnerList(outcome.Owners), joined = outcome.Joined });

/// <summary>Records a program as the caller, or joins the timer that already records it.</summary>
public async Task<object> Post(RecordOwnerRequest request)
{
var service = PluginServices.RecordingOwners;
if (service == null) return NotReady();
var user = AuthHelpers.GetCurrentUser(Request, _authContext);
if (user == null) return NoUser();
if (user.Policy?.EnableLiveTvManagement != true) return NotAllowed();
if (!OwnersEnabled()) return OwnersNotFound();

var body = await MoonfinJson.ReadBodyAsync<RecordOwnerBody>(request.RequestStream).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(body?.ProgramId)) return Json(400, new { error = "programId is required." });
if (!ProgramVisible(body!.ProgramId!, user.Id)) return Json(404, new { error = "No guide program with that id" });

var attempt = await service.TryRecordProgramAsync(body.ProgramId!, user.Id, CancellationToken.None).ConfigureAwait(false);
return attempt.Outcome == null
? Json(409, new { error = attempt.ErrorOr("The server could not schedule the recording.") })
: OwnershipResult(attempt.Outcome);
}

/// <summary>Records a program's series as the caller, or joins the rule that already records it.</summary>
public async Task<object> Post(RecordSeriesOwnerRequest request)
{
var service = PluginServices.RecordingOwners;
if (service == null) return NotReady();
var user = AuthHelpers.GetCurrentUser(Request, _authContext);
if (user == null) return NoUser();
if (user.Policy?.EnableLiveTvManagement != true) return NotAllowed();
if (!OwnersEnabled()) return OwnersNotFound();

var body = await MoonfinJson.ReadBodyAsync<RecordOwnerBody>(request.RequestStream).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(body?.ProgramId)) return Json(400, new { error = "programId is required." });
if (!ProgramVisible(body!.ProgramId!, user.Id)) return Json(404, new { error = "No guide program with that id" });

var attempt = await service.TryRecordSeriesAsync(body.ProgramId!, user.Id, body.Settings, CancellationToken.None).ConfigureAwait(false);
return attempt.Outcome == null
? Json(409, new { error = attempt.ErrorOr("The server could not create the series recording.") })
: OwnershipResult(attempt.Outcome);
}

/// <summary>Adds the caller to the owners of an existing timer, series rule or recording.</summary>
public async Task<object> Post(ClaimOwnerRequest request)
{
var service = PluginServices.RecordingOwners;
if (service == null) return NotReady();
var user = AuthHelpers.GetCurrentUser(Request, _authContext);
if (user == null) return NoUser();
if (user.Policy?.EnableLiveTvAccess != true) return NotAllowed();
if (!OwnersEnabled()) return OwnersNotFound();

var body = await MoonfinJson.ReadBodyAsync<ClaimOwnerBody>(request.RequestStream).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(body?.Id)) return Json(400, new { error = "id is required." });

OwnedKind kind;
switch (body!.Kind?.ToLowerInvariant())
{
case "timer": kind = OwnedKind.Timer; break;
case "series": kind = OwnedKind.Series; break;
case "item": kind = OwnedKind.Item; break;
default: return Json(400, new { error = "kind must be timer, series or item." });
}

var id = body.Id!;
if (kind == OwnedKind.Item)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
var itemId = ResolveItem(id);
if (itemId == null || PluginServices.RecordingHost?.IsVisibleTo(itemId.Value, user.Id) != true)
{
return Json(404, new { error = "No recording with that id" });
}

id = itemId.Value.ToString("N");
}

var owners = await service.ClaimAsync(kind, id, user.Id, CancellationToken.None).ConfigureAwait(false);
return owners == null
? Json(404, new { error = "Nothing to claim with that id" })
: Json(new { owners = OwnerList(owners) });
}

/// <summary>The owners of the given timers, series rules and recordings, in one call.</summary>
public async Task<object> Post(LookupOwnersRequest request)
{
var service = PluginServices.RecordingOwners;
if (service == null) return NotReady();
var user = AuthHelpers.GetCurrentUser(Request, _authContext);
if (user == null) return NoUser();
if (user.Policy?.EnableLiveTvAccess != true) return NotAllowed();
if (!OwnersEnabled()) return OwnersNotFound();

var body = await MoonfinJson.ReadBodyAsync<LookupOwnersBody>(request.RequestStream).ConfigureAwait(false);
var itemIds = (body?.ItemIds ?? new System.Collections.Generic.List<string>())
.Select(s => ResolveItem(s?.Trim()))
.Where(id => id != null)
.Select(id => id!.Value)
.Distinct()
.ToList();

var lookup = await service.LookupAsync(
body?.TimerIds ?? new System.Collections.Generic.List<string>(),
body?.SeriesTimerIds ?? new System.Collections.Generic.List<string>(),
itemIds,
user.Id,
CancellationToken.None).ConfigureAwait(false);

var timers = lookup.Timers.ToDictionary(p => p.Key, p => OwnerList(p.Value));
var seriesTimers = lookup.SeriesTimers.ToDictionary(p => p.Key, p => OwnerList(p.Value));
var items = lookup.Items.ToDictionary(p => ClientId(p.Key.ToString("N")), p => OwnerList(p.Value));

// recordingItemIds is left out, not sent as null, when the server can't tell: clients
// read a missing field as "unknown".
return lookup.RecordingItemIds == null
? Json(new { timers, seriesTimers, items })
: Json(new { timers, seriesTimers, items, recordingItemIds = lookup.RecordingItemIds.Select(i => ClientId(i.ToString("N"))).ToArray() });
}

/// <summary>Everything the caller owns. Timer ids may be stale; clients intersect them with the live timer list.</summary>
public async Task<object> Get(GetMyOwnedRequest request)
{
var service = PluginServices.RecordingOwners;
if (service == null) return NotReady();
var user = AuthHelpers.GetCurrentUser(Request, _authContext);
if (user == null) return NoUser();
if (user.Policy?.EnableLiveTvAccess != true) return NotAllowed();
if (!OwnersEnabled()) return OwnersNotFound();

var mine = await service.GetMineAsync(user.Id, CancellationToken.None).ConfigureAwait(false);
return Json(new
{
timerIds = mine.TimerIds,
seriesTimerIds = mine.SeriesTimerIds,
itemIds = mine.ItemIds.Select(i => ClientId(i.ToString("N"))).ToArray(),
});
}

// Emby clients send numeric item ids, and the feature keys items by their Guid.
private static Guid? ResolveItem(string? id)
{
Expand Down
8 changes: 8 additions & 0 deletions Emby/Emby.Plugins.Moonfin/Api/SettingsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ private bool TryAuthorizedSync([NotNullWhen(true)] out Guid? userId, [NotNullWhe
return true;
}

/// <summary>
/// Ping's recordingOwnersSupported: the setting, but only once the owners service runs, so a
/// client that pings during startup isn't sent to endpoints that would answer 503.
/// </summary>
internal static bool RecordingOwnersSupported(PluginConfiguration? config, bool serviceReady) =>
serviceReady && (config?.LiveTvRecordingOwners ?? true);

public object Get(GetPingRequest request)
{
var config = Plugin.Instance?.Configuration;
Expand Down Expand Up @@ -101,6 +108,7 @@ public object Get(GetPingRequest request)
smartSearchEnabled = config?.SmartSearchEnabled ?? false,
recommendationsSupported = config?.RecommendationsProviderEnabled ?? true,
incompleteRecordingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true,
recordingOwnersSupported = RecordingOwnersSupported(config, PluginServices.RecordingOwners != null),
extendedCompleteShowingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true,
clientLogSupported = config?.EnableClientLogUpload ?? false,
calendarAvailable = seerrEnabled
Expand Down
9 changes: 9 additions & 0 deletions Emby/Emby.Plugins.Moonfin/Pages/configPage.html
Original file line number Diff line number Diff line change
Expand Up @@ -5280,6 +5280,15 @@ <h3 class="sectionTitle">Uploaded Themes</h3>
<section class="moonfinTabPanel" data-tab="livetv">
<div class="verticalSection">
<h3 class="sectionTitle">Live TV Recordings</h3>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input type="checkbox" id="LiveTvRecordingOwners" is="emby-checkbox" />
<span>Track who records each Live TV recording (My Recordings)</span>
</label>
<div class="fieldDescription">
Remembers which users scheduled each recording, so Moonfin can show a My Recordings list and who else records a show.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input type="checkbox" id="LiveTvDetectIncompleteRecordings" is="emby-checkbox" />
Expand Down
2 changes: 2 additions & 0 deletions Emby/Emby.Plugins.Moonfin/Pages/moonfin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2887,6 +2887,7 @@ define(['baseView', 'loading', 'emby-input', 'emby-button', 'emby-checkbox', 'em
view.querySelector('#WebEnableWebRtcScan').checked = config.WebEnableWebRtcScan !== false;
view.querySelector('#EnableClientLogUpload').checked = config.EnableClientLogUpload !== false;
view.querySelector('#LiveTvDetectIncompleteRecordings').checked = config.LiveTvDetectIncompleteRecordings !== false;
view.querySelector('#LiveTvRecordingOwners').checked = config.LiveTvRecordingOwners !== false;
view.querySelector('#SmartSearchEnabled').checked = config.SmartSearchEnabled === true;
view.querySelector('#SmartSearchModel').value = config.SmartSearchModel || 'english';
view.querySelector('#WatchPartiesEnabled').checked = config.WatchPartiesEnabled !== false;
Expand Down Expand Up @@ -3301,6 +3302,7 @@ define(['baseView', 'loading', 'emby-input', 'emby-button', 'emby-checkbox', 'em
config.WebEnableWebRtcScan = view.querySelector('#WebEnableWebRtcScan').checked;
config.EnableClientLogUpload = view.querySelector('#EnableClientLogUpload').checked;
config.LiveTvDetectIncompleteRecordings = view.querySelector('#LiveTvDetectIncompleteRecordings').checked;
config.LiveTvRecordingOwners = view.querySelector('#LiveTvRecordingOwners').checked;
config.SmartSearchEnabled = view.querySelector('#SmartSearchEnabled').checked;
config.SmartSearchModel = view.querySelector('#SmartSearchModel').value || 'english';
config.WatchPartiesEnabled = view.querySelector('#WatchPartiesEnabled').checked;
Expand Down
3 changes: 3 additions & 0 deletions Emby/Emby.Plugins.Moonfin/PluginConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,9 @@ public bool EnsureWebhookSecret()
/// </summary>
public bool LiveTvDetectIncompleteRecordings { get; set; } = true;

/// <summary>Tracks which users own each Live TV timer, series rule and recording, for My Recordings.</summary>
public bool LiveTvRecordingOwners { get; set; } = true;

/// <summary>When a Live TV recording comes out incomplete, schedule the earliest later showing of the same episode.</summary>
public bool LiveTvAutoRecordCompleteShowing { get; set; }

Expand Down
Loading