Skip to content

Commit

Permalink
more cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
crobibero committed Jun 14, 2024
1 parent 7a08a85 commit eab72a5
Show file tree
Hide file tree
Showing 12 changed files with 115 additions and 128 deletions.
28 changes: 15 additions & 13 deletions Jellyfin.Plugin.NextPVR/Configuration/PluginConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using Jellyfin.Plugin.NextPVR.Entities;

Expand All @@ -23,20 +23,22 @@ public PluginConfiguration()
PollInterval = 20;
BackendVersion = 0;
// Initialise this
GenreMappings = new SerializableDictionary<string, List<string>>();
GenreMappings["GENRESPORT"] = new List<string>()
GenreMappings = new SerializableDictionary<string, List<string>>
{
"Sports",
"Football",
"Baseball",
"Basketball",
"Hockey",
"Soccer"
["GENRESPORT"] =
[
"Sports",
"Football",
"Baseball",
"Basketball",
"Hockey",
"Soccer"
],
["GENRENEWS"] = ["News"],
["GENREKIDS"] = ["Kids", "Children"],
["GENREMOVIE"] = ["Movie", "Film"],
["GENRELIVE"] = ["Awards"]
};
GenreMappings["GENRENEWS"] = new List<string>() { "News" };
GenreMappings["GENREKIDS"] = new List<string>() { "Kids", "Children" };
GenreMappings["GENREMOVIE"] = new List<string>() { "Movie", "Film" };
GenreMappings["GENRELIVE"] = new List<string>() { "Awards" };
}

public string WebServiceUrl { get; set; }
Expand Down
138 changes: 60 additions & 78 deletions Jellyfin.Plugin.NextPVR/LiveTvService.cs

Large diffs are not rendered by default.

29 changes: 16 additions & 13 deletions Jellyfin.Plugin.NextPVR/RecordingsChannel.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
Expand Down Expand Up @@ -37,15 +37,15 @@ public class RecordingsChannel : IChannel, IHasCacheKey, ISupportsDelete, ISuppo
private IEnumerable<MyRecordingInfo> _allRecordings;
private bool _useCachedRecordings = false;
private DateTime _cachedRecordingModificationTime;
private string _cachekeyBase;
private string _cacheKeyBase;
private int _pollInterval = -1;

public RecordingsChannel(IApplicationPaths applicationPaths, ILibraryManager libraryManager, IFileSystem fileSystem, ILogger<RecordingsChannel> logger)
{
_fileSystem = fileSystem;
_logger = logger;
string channelId = libraryManager.GetNewItemId($"Channel {Name}", typeof(Channel)).ToString("N", CultureInfo.InvariantCulture);
string version = BaseExtensions.GetMD5($"{DataVersion}2").ToString("N", CultureInfo.InvariantCulture);
string version = $"{DataVersion}2".GetMD5().ToString("N", CultureInfo.InvariantCulture);
_recordingCacheDirectory = Path.Join(applicationPaths.CachePath, "channels", channelId, version);
CleanCache(true);
_cancellationToken = new CancellationTokenSource();
Expand All @@ -57,7 +57,7 @@ public RecordingsChannel(IApplicationPaths applicationPaths, ILibraryManager lib
public string Description => "NextPVR Recordings";

#pragma warning disable CA1819
public string[] Attributes => new[] { "Recordings" };
public string[] Attributes => ["Recordings"];
#pragma warning restore CA1819

public string DataVersion => "1";
Expand Down Expand Up @@ -86,30 +86,33 @@ protected virtual void Dispose(bool disposing)
public string GetCacheKey(string userId)
{
DateTimeOffset dto = LiveTvService.Instance.RecordingModificationTime;
return $"{dto.ToUnixTimeSeconds()}-{_cachekeyBase}";
return $"{dto.ToUnixTimeSeconds()}-{_cacheKeyBase}";
}

private void CleanCache(bool cleanAll = false)
{
if (!string.IsNullOrEmpty(_recordingCacheDirectory) && Directory.Exists(_recordingCacheDirectory))
{
string[] cachedJson = Directory.GetFiles(_recordingCacheDirectory, "*.json");
_logger.LogInformation("Cleaning JSON cache {0} {1}", _recordingCacheDirectory, cachedJson.Length);
_logger.LogInformation("Cleaning JSON cache {CacheDirectory} {FileCount}", _recordingCacheDirectory, cachedJson.Length);
foreach (string fileName in cachedJson)
{
if (cleanAll == true || _fileSystem.GetLastWriteTimeUtc(fileName).Add(TimeSpan.FromHours(3)) <= DateTimeOffset.UtcNow)
if (cleanAll || _fileSystem.GetLastWriteTimeUtc(fileName).Add(TimeSpan.FromHours(3)) <= DateTimeOffset.UtcNow)
{
_fileSystem.DeleteFile(fileName);
}
}
}

return;
}

public InternalChannelFeatures GetChannelFeatures()
{
return new InternalChannelFeatures { ContentTypes = new List<ChannelMediaContentType> { ChannelMediaContentType.Movie, ChannelMediaContentType.Episode, ChannelMediaContentType.Clip }, MediaTypes = new List<ChannelMediaType> { ChannelMediaType.Audio, ChannelMediaType.Video }, SupportsContentDownloading = true };
return new InternalChannelFeatures
{
ContentTypes = [ChannelMediaContentType.Movie, ChannelMediaContentType.Episode, ChannelMediaContentType.Clip],
MediaTypes = [ChannelMediaType.Audio, ChannelMediaType.Video],
SupportsContentDownloading = true
};
}

public Task<DynamicImageResponse> GetChannelImage(ImageType type, CancellationToken cancellationToken)
Expand Down Expand Up @@ -315,15 +318,15 @@ private async Task<bool> GetRecordingsAsync(string name, CancellationToken cance
_logger.LogDebug("{0} Reload cache", name);
_allRecordings = await service.GetAllRecordingsAsync(cancellationToken).ConfigureAwait(false);
int maxId = _allRecordings.Max(r => int.Parse(r.Id, CultureInfo.InvariantCulture));
int inProcessCount = _allRecordings.Where(r => r.Status == RecordingStatus.InProgress).Count();
int inProcessCount = _allRecordings.Count(r => r.Status == RecordingStatus.InProgress);
string keyBase = $"{maxId}-{inProcessCount}-{_allRecordings.Count()}";
if (keyBase != _cachekeyBase && !service.FlagRecordingChange)
if (keyBase != _cacheKeyBase && !service.FlagRecordingChange)
{
_logger.LogDebug("External recording list change {0}", keyBase);
CleanCache(true);
}

_cachekeyBase = keyBase;
_cacheKeyBase = keyBase;
_lastUpdate = DateTimeOffset.UtcNow;
service.FlagRecordingChange = false;
_useCachedRecordings = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class CancelDeleteRecordingResponse

if (root.Stat != "ok")
{
UtilsHelper.DebugInformation(logger, $"[NextPVR] RecordingError Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"RecordingError Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
return true;
}

Expand Down
4 changes: 2 additions & 2 deletions Jellyfin.Plugin.NextPVR/Responses/ChannelResponse.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -33,7 +33,7 @@ public async Task<IEnumerable<ChannelInfo>> GetChannels(Stream stream, ILogger<L

if (root.Channels != null)
{
UtilsHelper.DebugInformation(logger, $"[NextPVR] ChannelResponse: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"ChannelResponse: {JsonSerializer.Serialize(root, _jsonOptions)}");
return root.Channels.Select(i => new ChannelInfo
{
Name = i.ChannelName,
Expand Down
6 changes: 3 additions & 3 deletions Jellyfin.Plugin.NextPVR/Responses/InitializeResponse.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.IO;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using Jellyfin.Extensions.Json;
Expand All @@ -17,11 +17,11 @@ public async Task<bool> LoggedIn(Stream stream, ILogger<LiveTvService> logger)

if (!string.IsNullOrEmpty(root.Stat))
{
UtilsHelper.DebugInformation(logger, $"[NextPVR] Connection validation: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"Connection validation: {JsonSerializer.Serialize(root, _jsonOptions)}");
return root.Stat == "ok";
}

logger.LogError("[NextPVR] Failed to validate your connection with NextPVR");
logger.LogError("Failed to validate your connection with NextPVR");
throw new JsonException("Failed to validate your connection with NextPVR.");
}

Expand Down
4 changes: 2 additions & 2 deletions Jellyfin.Plugin.NextPVR/Responses/InstantiateResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ public async Task<ClientKeys> GetClientKeys(Stream stream, ILogger<LiveTvService

if (root.Sid != null && root.Salt != null)
{
UtilsHelper.DebugInformation(logger, $"[NextPVR] ClientKeys: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"ClientKeys: {JsonSerializer.Serialize(root, _jsonOptions)}");
return root;
}

logger.LogError("[NextPVR] Failed to validate the ClientKeys from NextPVR");
logger.LogError("Failed to validate the ClientKeys from NextPVR");
throw new JsonException("Failed to load the ClientKeys from NextPVR.");
}
catch
Expand Down
2 changes: 1 addition & 1 deletion Jellyfin.Plugin.NextPVR/Responses/LastUpdateResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class LastUpdateResponse
public async Task<DateTimeOffset> GetUpdateTime(Stream stream, ILogger<LiveTvService> logger)
{
var root = await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(logger, $"[NextPVR] LastUpdate Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"LastUpdate Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
return DateTimeOffset.FromUnixTimeSeconds(root.LastUpdate);
}

Expand Down
2 changes: 1 addition & 1 deletion Jellyfin.Plugin.NextPVR/Responses/ListingsResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public ListingsResponse(string baseUrl)
public async Task<IEnumerable<ProgramInfo>> GetPrograms(Stream stream, string channelId, ILogger<LiveTvService> logger)
{
var root = await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(logger, $"[NextPVR] GetPrograms Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"GetPrograms Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
_channelId = channelId;
return root.Listings
.Select(i => i)
Expand Down
16 changes: 8 additions & 8 deletions Jellyfin.Plugin.NextPVR/Responses/RecordingResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,16 @@ public RecordingResponse(string baseUrl, ILogger<LiveTvService> logger)
_logger = logger;
}

public async Task<IEnumerable<MyRecordingInfo>> GetRecordings(Stream stream)
public async Task<IReadOnlyList<MyRecordingInfo>> GetRecordings(Stream stream)
{
if (stream == null)
{
_logger.LogError("[NextPVR] GetRecording stream == null");
_logger.LogError("GetRecording stream == null");
throw new ArgumentNullException(nameof(stream));
}

var root = await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(_logger, $"[NextPVR] GetRecordings Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(_logger, $"GetRecordings Response: {JsonSerializer.Serialize(root, _jsonOptions)}");

IEnumerable<MyRecordingInfo> recordings;
try
Expand All @@ -47,23 +47,23 @@ public async Task<IEnumerable<MyRecordingInfo>> GetRecordings(Stream stream)
}
catch (Exception err)
{
_logger.LogWarning(err, "[NextPVR] Get recordings");
_logger.LogWarning(err, "Get recordings");
throw;
}

return recordings;
return recordings.ToList();
}

public async Task<IEnumerable<TimerInfo>> GetTimers(Stream stream)
{
if (stream == null)
{
_logger.LogError("[NextPVR] GetTimers stream == null");
_logger.LogError("GetTimers stream == null");
throw new ArgumentNullException(nameof(stream));
}

var root = await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(_logger, $"[NextPVR] GetTimers Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(_logger, $"GetTimers Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
IEnumerable<TimerInfo> timers;
try
{
Expand All @@ -73,7 +73,7 @@ public async Task<IEnumerable<TimerInfo>> GetTimers(Stream stream)
}
catch (Exception err)
{
_logger.LogWarning(err, "[NextPVR] Get timers");
_logger.LogWarning(err, "Get timers");
throw;
}

Expand Down
6 changes: 3 additions & 3 deletions Jellyfin.Plugin.NextPVR/Responses/RecurringResponse.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
Expand Down Expand Up @@ -26,12 +26,12 @@ public async Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimers(Stream stream)
{
if (stream == null)
{
_logger.LogError("[NextPVR] GetSeriesTimers stream == null");
_logger.LogError("GetSeriesTimers stream == null");
throw new ArgumentNullException(nameof(stream));
}

var root = await JsonSerializer.DeserializeAsync<RootObject>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(_logger, $"[NextPVR] GetSeriesTimers Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(_logger, $"GetSeriesTimers Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
return root.Recurrings
.Select(i => i)
.Select(GetSeriesTimerInfo);
Expand Down
6 changes: 3 additions & 3 deletions Jellyfin.Plugin.NextPVR/Responses/SettingResponse.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.IO;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
Expand All @@ -15,7 +15,7 @@ public class SettingResponse
public async Task<bool> GetDefaultSettings(Stream stream, ILogger<LiveTvService> logger)
{
var root = await JsonSerializer.DeserializeAsync<ScheduleSettings>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(logger, $"[NextPVR] GetDefaultTimerInfo Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"GetDefaultTimerInfo Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
Plugin.Instance.Configuration.PostPaddingSeconds = root.PostPadding;
Plugin.Instance.Configuration.PrePaddingSeconds = root.PrePadding;
Plugin.Instance.Configuration.ShowRepeat = root.ShowNewInGuide;
Expand All @@ -26,7 +26,7 @@ public async Task<bool> GetDefaultSettings(Stream stream, ILogger<LiveTvService>
public async Task<string> GetSetting(Stream stream, ILogger<LiveTvService> logger)
{
var root = await JsonSerializer.DeserializeAsync<SettingValue>(stream, _jsonOptions).ConfigureAwait(false);
UtilsHelper.DebugInformation(logger, $"[NextPVR] GetSetting Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
UtilsHelper.DebugInformation(logger, $"GetSetting Response: {JsonSerializer.Serialize(root, _jsonOptions)}");
return root.Value;
}

Expand Down

0 comments on commit eab72a5

Please sign in to comment.