Merge pull request #6121 from Bond-009/warn52

Fix some warnings
pull/6133/head
Bond-009 4 years ago committed by GitHub
commit 9712fa85c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -25,6 +25,11 @@ namespace Emby.Server.Implementations.AppBase
private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>(); private readonly ConcurrentDictionary<string, object> _configurations = new ConcurrentDictionary<string, object>();
/// <summary>
/// The _configuration sync lock.
/// </summary>
private readonly object _configurationSyncLock = new object();
private ConfigurationStore[] _configurationStores = Array.Empty<ConfigurationStore>(); private ConfigurationStore[] _configurationStores = Array.Empty<ConfigurationStore>();
private IConfigurationFactory[] _configurationFactories = Array.Empty<IConfigurationFactory>(); private IConfigurationFactory[] _configurationFactories = Array.Empty<IConfigurationFactory>();
@ -33,11 +38,6 @@ namespace Emby.Server.Implementations.AppBase
/// </summary> /// </summary>
private bool _configurationLoaded; private bool _configurationLoaded;
/// <summary>
/// The _configuration sync lock.
/// </summary>
private readonly object _configurationSyncLock = new object();
/// <summary> /// <summary>
/// The _configuration. /// The _configuration.
/// </summary> /// </summary>

@ -33,7 +33,8 @@ namespace Emby.Server.Implementations.AppBase
} }
catch (Exception) catch (Exception)
{ {
configuration = Activator.CreateInstance(type) ?? throw new ArgumentException($"Provided path ({type}) is not valid.", nameof(type)); // Note: CreateInstance returns null for Nullable<T>, e.g. CreateInstance(typeof(int?)) returns null.
configuration = Activator.CreateInstance(type)!;
} }
using var stream = new MemoryStream(buffer?.Length ?? 0); using var stream = new MemoryStream(buffer?.Length ?? 0);

@ -54,8 +54,8 @@ namespace Emby.Server.Implementations.EntryPoints
try try
{ {
_udpServer = new UdpServer(_logger, _appHost, _config); _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber);
_udpServer.Start(PortNumber, _cancellationTokenSource.Token); _udpServer.Start(_cancellationTokenSource.Token);
} }
catch (SocketException ex) catch (SocketException ex)
{ {

@ -1,5 +1,3 @@
#nullable disable
#pragma warning disable CS1591 #pragma warning disable CS1591
using System; using System;
@ -28,7 +26,7 @@ namespace Emby.Server.Implementations.EntryPoints
private readonly Dictionary<Guid, List<BaseItem>> _changedItems = new Dictionary<Guid, List<BaseItem>>(); private readonly Dictionary<Guid, List<BaseItem>> _changedItems = new Dictionary<Guid, List<BaseItem>>();
private readonly object _syncLock = new object(); private readonly object _syncLock = new object();
private Timer _updateTimer; private Timer? _updateTimer;
public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IUserManager userManager) public UserDataChangeNotifier(IUserDataManager userDataManager, ISessionManager sessionManager, IUserManager userManager)
{ {
@ -44,7 +42,7 @@ namespace Emby.Server.Implementations.EntryPoints
return Task.CompletedTask; return Task.CompletedTask;
} }
void OnUserDataManagerUserDataSaved(object sender, UserDataSaveEventArgs e) private void OnUserDataManagerUserDataSaved(object? sender, UserDataSaveEventArgs e)
{ {
if (e.SaveReason == UserDataSaveReason.PlaybackProgress) if (e.SaveReason == UserDataSaveReason.PlaybackProgress)
{ {
@ -66,7 +64,7 @@ namespace Emby.Server.Implementations.EntryPoints
_updateTimer.Change(UpdateDuration, Timeout.Infinite); _updateTimer.Change(UpdateDuration, Timeout.Infinite);
} }
if (!_changedItems.TryGetValue(e.UserId, out List<BaseItem> keys)) if (!_changedItems.TryGetValue(e.UserId, out List<BaseItem>? keys))
{ {
keys = new List<BaseItem>(); keys = new List<BaseItem>();
_changedItems[e.UserId] = keys; _changedItems[e.UserId] = keys;
@ -89,7 +87,7 @@ namespace Emby.Server.Implementations.EntryPoints
} }
} }
private void UpdateTimerCallback(object state) private void UpdateTimerCallback(object? state)
{ {
lock (_syncLock) lock (_syncLock)
{ {

@ -1,5 +1,3 @@
#nullable disable
#pragma warning disable CS1591 #pragma warning disable CS1591
using System; using System;

@ -1,21 +1,23 @@
#pragma warning disable CS1591
using System.Collections.Generic; using System.Collections.Generic;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.LiveTv;
namespace Emby.Server.Implementations.LiveTv namespace Emby.Server.Implementations.LiveTv
{ {
/// <summary>
/// <see cref="IConfigurationFactory" /> implementation for <see cref="LiveTvOptions" />.
/// </summary>
public class LiveTvConfigurationFactory : IConfigurationFactory public class LiveTvConfigurationFactory : IConfigurationFactory
{ {
/// <inheritdoc />
public IEnumerable<ConfigurationStore> GetConfigurations() public IEnumerable<ConfigurationStore> GetConfigurations()
{ {
return new ConfigurationStore[] return new ConfigurationStore[]
{ {
new ConfigurationStore new ConfigurationStore
{ {
ConfigurationType = typeof(LiveTvOptions), ConfigurationType = typeof(LiveTvOptions),
Key = "livetv" Key = "livetv"
} }
}; };
} }

@ -2266,7 +2266,7 @@ namespace Emby.Server.Implementations.LiveTv
if (dataSourceChanged) if (dataSourceChanged)
{ {
_taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>(); _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
} }
return info; return info;
@ -2309,7 +2309,7 @@ namespace Emby.Server.Implementations.LiveTv
_config.SaveConfiguration("livetv", config); _config.SaveConfiguration("livetv", config);
_taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>(); _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
return info; return info;
} }
@ -2321,7 +2321,7 @@ namespace Emby.Server.Implementations.LiveTv
config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray(); config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
_config.SaveConfiguration("livetv", config); _config.SaveConfiguration("livetv", config);
_taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>(); _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
} }
public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelId, string providerChannelId) public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelId, string providerChannelId)
@ -2355,7 +2355,7 @@ namespace Emby.Server.Implementations.LiveTv
var tunerChannelMappings = var tunerChannelMappings =
tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList(); tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
_taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>(); _taskManager.CancelIfRunningAndQueue<RefreshGuideScheduledTask>();
return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelId, StringComparison.OrdinalIgnoreCase)); return tunerChannelMappings.First(i => string.Equals(i.Id, tunerChannelId, StringComparison.OrdinalIgnoreCase));
} }

@ -1,7 +1,6 @@
#pragma warning disable CS1591
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.LiveTv;
@ -10,34 +9,55 @@ using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.LiveTv namespace Emby.Server.Implementations.LiveTv
{ {
public class RefreshChannelsScheduledTask : IScheduledTask, IConfigurableScheduledTask /// <summary>
/// The "Refresh Guide" scheduled task.
/// </summary>
public class RefreshGuideScheduledTask : IScheduledTask, IConfigurableScheduledTask
{ {
private readonly ILiveTvManager _liveTvManager; private readonly ILiveTvManager _liveTvManager;
private readonly IConfigurationManager _config; private readonly IConfigurationManager _config;
public RefreshChannelsScheduledTask(ILiveTvManager liveTvManager, IConfigurationManager config) /// <summary>
/// Initializes a new instance of the <see cref="RefreshGuideScheduledTask"/> class.
/// </summary>
/// <param name="liveTvManager">The live tv manager.</param>
/// <param name="config">The configuration manager.</param>
public RefreshGuideScheduledTask(ILiveTvManager liveTvManager, IConfigurationManager config)
{ {
_liveTvManager = liveTvManager; _liveTvManager = liveTvManager;
_config = config; _config = config;
} }
/// <inheritdoc />
public string Name => "Refresh Guide"; public string Name => "Refresh Guide";
/// <inheritdoc />
public string Description => "Downloads channel information from live tv services."; public string Description => "Downloads channel information from live tv services.";
/// <inheritdoc />
public string Category => "Live TV"; public string Category => "Live TV";
public Task Execute(System.Threading.CancellationToken cancellationToken, IProgress<double> progress) /// <inheritdoc />
public bool IsHidden => _liveTvManager.Services.Count == 1 && GetConfiguration().TunerHosts.Length == 0;
/// <inheritdoc />
public bool IsEnabled => true;
/// <inheritdoc />
public bool IsLogged => true;
/// <inheritdoc />
public string Key => "RefreshGuide";
/// <inheritdoc />
public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
{ {
var manager = (LiveTvManager)_liveTvManager; var manager = (LiveTvManager)_liveTvManager;
return manager.RefreshChannels(progress, cancellationToken); return manager.RefreshChannels(progress, cancellationToken);
} }
/// <summary> /// <inheritdoc />
/// Creates the triggers that define when the task will run.
/// </summary>
/// <returns>IEnumerable{BaseTaskTrigger}.</returns>
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{ {
return new[] return new[]
@ -51,13 +71,5 @@ namespace Emby.Server.Implementations.LiveTv
{ {
return _config.GetConfiguration<LiveTvOptions>("livetv"); return _config.GetConfiguration<LiveTvOptions>("livetv");
} }
public bool IsHidden => _liveTvManager.Services.Count == 1 && GetConfiguration().TunerHosts.Length == 0;
public bool IsEnabled => true;
public bool IsLogged => true;
public string Key => "RefreshGuide";
} }
} }

@ -40,6 +40,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
public virtual bool IsSupported => true; public virtual bool IsSupported => true;
protected abstract Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken); protected abstract Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
public abstract string Type { get; } public abstract string Type { get; }
public async Task<List<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken) public async Task<List<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken)

@ -583,7 +583,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
Logger, Logger,
Config, Config,
_appHost, _appHost,
_networkManager,
_streamHelper); _streamHelper);
} }
@ -624,7 +623,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
Logger, Logger,
Config, Config,
_appHost, _appHost,
_networkManager,
_streamHelper); _streamHelper);
} }

@ -12,7 +12,6 @@ using System.Net.Sockets;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Dto; using MediaBrowser.Model.Dto;
@ -30,7 +29,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
private readonly IServerApplicationHost _appHost; private readonly IServerApplicationHost _appHost;
private readonly IHdHomerunChannelCommands _channelCommands; private readonly IHdHomerunChannelCommands _channelCommands;
private readonly int _numTuners; private readonly int _numTuners;
private readonly INetworkManager _networkManager;
public HdHomerunUdpStream( public HdHomerunUdpStream(
MediaSourceInfo mediaSource, MediaSourceInfo mediaSource,
@ -42,12 +40,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
ILogger logger, ILogger logger,
IConfigurationManager configurationManager, IConfigurationManager configurationManager,
IServerApplicationHost appHost, IServerApplicationHost appHost,
INetworkManager networkManager,
IStreamHelper streamHelper) IStreamHelper streamHelper)
: base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper) : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
{ {
_appHost = appHost; _appHost = appHost;
_networkManager = networkManager;
OriginalStreamId = originalStreamId; OriginalStreamId = originalStreamId;
_channelCommands = channelCommands; _channelCommands = channelCommands;
_numTuners = numTuners; _numTuners = numTuners;
@ -128,7 +124,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
using (udpClient) using (udpClient)
using (hdHomerunManager) using (hdHomerunManager)
{ {
if (!(ex is OperationCanceledException)) if (ex is not OperationCanceledException)
{ {
Logger.LogError(ex, "Error opening live stream:"); Logger.LogError(ex, "Error opening live stream:");
} }

@ -29,6 +29,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{ {
public class M3UTunerHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost public class M3UTunerHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
{ {
private static readonly string[] _disallowedSharedStreamExtensions =
{
".mkv",
".mp4",
".m3u8",
".mpd"
};
private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerApplicationHost _appHost; private readonly IServerApplicationHost _appHost;
private readonly INetworkManager _networkManager; private readonly INetworkManager _networkManager;
@ -67,7 +75,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{ {
var channelIdPrefix = GetFullChannelIdPrefix(info); var channelIdPrefix = GetFullChannelIdPrefix(info);
return await new M3uParser(Logger, _httpClientFactory, _appHost) return await new M3uParser(Logger, _httpClientFactory)
.Parse(info, channelIdPrefix, cancellationToken) .Parse(info, channelIdPrefix, cancellationToken)
.ConfigureAwait(false); .ConfigureAwait(false);
} }
@ -88,14 +96,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return Task.FromResult(list); return Task.FromResult(list);
} }
private static readonly string[] _disallowedSharedStreamExtensions =
{
".mkv",
".mp4",
".m3u8",
".mpd"
};
protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken) protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
{ {
var tunerCount = info.TunerCount; var tunerCount = info.TunerCount;
@ -130,7 +130,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
public async Task Validate(TunerHostInfo info) public async Task Validate(TunerHostInfo info)
{ {
using (var stream = await new M3uParser(Logger, _httpClientFactory, _appHost).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false)) using (var stream = await new M3uParser(Logger, _httpClientFactory).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false))
{ {
} }
} }

@ -21,15 +21,15 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{ {
public class M3uParser public class M3uParser
{ {
private const string ExtInfPrefix = "#EXTINF:";
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpClientFactory _httpClientFactory;
private readonly IServerApplicationHost _appHost;
public M3uParser(ILogger logger, IHttpClientFactory httpClientFactory, IServerApplicationHost appHost) public M3uParser(ILogger logger, IHttpClientFactory httpClientFactory)
{ {
_logger = logger; _logger = logger;
_httpClientFactory = httpClientFactory; _httpClientFactory = httpClientFactory;
_appHost = appHost;
} }
public async Task<List<ChannelInfo>> Parse(TunerHostInfo info, string channelIdPrefix, CancellationToken cancellationToken) public async Task<List<ChannelInfo>> Parse(TunerHostInfo info, string channelIdPrefix, CancellationToken cancellationToken)
@ -61,8 +61,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return File.OpenRead(info.Url); return File.OpenRead(info.Url);
} }
private const string ExtInfPrefix = "#EXTINF:";
private async Task<List<ChannelInfo>> GetChannelsAsync(TextReader reader, string channelIdPrefix, string tunerHostId) private async Task<List<ChannelInfo>> GetChannelsAsync(TextReader reader, string channelIdPrefix, string tunerHostId)
{ {
var channels = new List<ChannelInfo>(); var channels = new List<ChannelInfo>();

@ -91,8 +91,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
var taskCompletionSource = new TaskCompletionSource<bool>(); var taskCompletionSource = new TaskCompletionSource<bool>();
var now = DateTime.UtcNow;
_ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token); _ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
// OpenedMediaSource.Protocol = MediaProtocol.File; // OpenedMediaSource.Protocol = MediaProtocol.File;
@ -120,7 +118,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
if (!taskCompletionSource.Task.Result) if (!taskCompletionSource.Task.Result)
{ {
Logger.LogWarning("Zero bytes copied from stream {0} to {1} but no exception raised", GetType().Name, TempFilePath); Logger.LogWarning("Zero bytes copied from stream {0} to {1} but no exception raised", GetType().Name, TempFilePath);
throw new EndOfStreamException(String.Format(CultureInfo.InvariantCulture, "Zero bytes copied from stream {0}", GetType().Name)); throw new EndOfStreamException(string.Format(CultureInfo.InvariantCulture, "Zero bytes copied from stream {0}", GetType().Name));
} }
} }

@ -455,7 +455,8 @@ namespace Emby.Server.Implementations.Plugins
try try
{ {
_logger.LogDebug("Creating instance of {Type}", type); _logger.LogDebug("Creating instance of {Type}", type);
var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider, type); // _appHost.ServiceProvider is already assigned when we create the plugins
var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider!, type);
if (plugin == null) if (plugin == null)
{ {
// Create a dummy record for the providers. // Create a dummy record for the providers.

@ -711,11 +711,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info)); throw new ArgumentException("Info did not contain a TimeOfDayTicks.", nameof(info));
} }
return new DailyTrigger return new DailyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), options);
{
TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
TaskOptions = options
};
} }
if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase)) if (info.Type.Equals(nameof(WeeklyTrigger), StringComparison.OrdinalIgnoreCase))
@ -730,12 +726,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info)); throw new ArgumentException("Info did not contain a DayOfWeek.", nameof(info));
} }
return new WeeklyTrigger return new WeeklyTrigger(TimeSpan.FromTicks(info.TimeOfDayTicks.Value), info.DayOfWeek.Value, options);
{
TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
DayOfWeek = info.DayOfWeek.Value,
TaskOptions = options
};
} }
if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase)) if (info.Type.Equals(nameof(IntervalTrigger), StringComparison.OrdinalIgnoreCase))
@ -745,16 +736,12 @@ namespace Emby.Server.Implementations.ScheduledTasks
throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info)); throw new ArgumentException("Info did not contain a IntervalTicks.", nameof(info));
} }
return new IntervalTrigger return new IntervalTrigger(TimeSpan.FromTicks(info.IntervalTicks.Value), options);
{
Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
TaskOptions = options
};
} }
if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase)) if (info.Type.Equals(nameof(StartupTrigger), StringComparison.OrdinalIgnoreCase))
{ {
return new StartupTrigger(); return new StartupTrigger(options);
} }
throw new ArgumentException("Unrecognized trigger type: " + info.Type); throw new ArgumentException("Unrecognized trigger type: " + info.Type);

@ -1,5 +1,3 @@
#nullable disable
using System; using System;
using System.Threading; using System.Threading;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
@ -10,29 +8,31 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <summary> /// <summary>
/// Represents a task trigger that fires everyday. /// Represents a task trigger that fires everyday.
/// </summary> /// </summary>
public class DailyTrigger : ITaskTrigger public sealed class DailyTrigger : ITaskTrigger
{ {
/// <summary> private readonly TimeSpan _timeOfDay;
/// Occurs when [triggered]. private Timer? _timer;
/// </summary>
public event EventHandler<EventArgs> Triggered;
/// <summary> /// <summary>
/// Gets or sets the time of day to trigger the task to run. /// Initializes a new instance of the <see cref="DailyTrigger"/> class.
/// </summary> /// </summary>
/// <value>The time of day.</value> /// <param name="timeofDay">The time of day to trigger the task to run.</param>
public TimeSpan TimeOfDay { get; set; } /// <param name="taskOptions">The options of this task.</param>
public DailyTrigger(TimeSpan timeofDay, TaskOptions taskOptions)
{
_timeOfDay = timeofDay;
TaskOptions = taskOptions;
}
/// <summary> /// <summary>
/// Gets or sets the options of this task. /// Occurs when [triggered].
/// </summary> /// </summary>
public TaskOptions TaskOptions { get; set; } public event EventHandler<EventArgs>? Triggered;
/// <summary> /// <summary>
/// Gets or sets the timer. /// Gets the options of this task.
/// </summary> /// </summary>
/// <value>The timer.</value> public TaskOptions TaskOptions { get; }
private Timer Timer { get; set; }
/// <summary> /// <summary>
/// Stars waiting for the trigger action. /// Stars waiting for the trigger action.
@ -47,14 +47,14 @@ namespace Emby.Server.Implementations.ScheduledTasks
var now = DateTime.Now; var now = DateTime.Now;
var triggerDate = now.TimeOfDay > TimeOfDay ? now.Date.AddDays(1) : now.Date; var triggerDate = now.TimeOfDay > _timeOfDay ? now.Date.AddDays(1) : now.Date;
triggerDate = triggerDate.Add(TimeOfDay); triggerDate = triggerDate.Add(_timeOfDay);
var dueTime = triggerDate - now; var dueTime = triggerDate - now;
logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime); logger.LogInformation("Daily trigger for {Task} set to fire at {TriggerDate:yyyy-MM-dd HH:mm:ss.fff zzz}, which is {DueTime:c} from now.", taskName, triggerDate, dueTime);
Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1)); _timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
} }
/// <summary> /// <summary>
@ -70,10 +70,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary> /// </summary>
private void DisposeTimer() private void DisposeTimer()
{ {
if (Timer != null) _timer?.Dispose();
{
Timer.Dispose();
}
} }
/// <summary> /// <summary>

@ -1,5 +1,3 @@
#nullable disable
using System; using System;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -11,31 +9,32 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <summary> /// <summary>
/// Represents a task trigger that runs repeatedly on an interval. /// Represents a task trigger that runs repeatedly on an interval.
/// </summary> /// </summary>
public class IntervalTrigger : ITaskTrigger public sealed class IntervalTrigger : ITaskTrigger
{ {
private readonly TimeSpan _interval;
private DateTime _lastStartDate; private DateTime _lastStartDate;
private Timer? _timer;
/// <summary> /// <summary>
/// Occurs when [triggered]. /// Initializes a new instance of the <see cref="IntervalTrigger"/> class.
/// </summary>
public event EventHandler<EventArgs> Triggered;
/// <summary>
/// Gets or sets the interval.
/// </summary> /// </summary>
/// <value>The interval.</value> /// <param name="interval">The interval.</param>
public TimeSpan Interval { get; set; } /// <param name="taskOptions">The options of this task.</param>
public IntervalTrigger(TimeSpan interval, TaskOptions taskOptions)
{
_interval = interval;
TaskOptions = taskOptions;
}
/// <summary> /// <summary>
/// Gets or sets the options of this task. /// Occurs when [triggered].
/// </summary> /// </summary>
public TaskOptions TaskOptions { get; set; } public event EventHandler<EventArgs>? Triggered;
/// <summary> /// <summary>
/// Gets or sets the timer. /// Gets the options of this task.
/// </summary> /// </summary>
/// <value>The timer.</value> public TaskOptions TaskOptions { get; }
private Timer Timer { get; set; }
/// <summary> /// <summary>
/// Stars waiting for the trigger action. /// Stars waiting for the trigger action.
@ -57,7 +56,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
} }
else else
{ {
triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate }.Max().Add(Interval); triggerDate = new[] { lastResult.EndTimeUtc, _lastStartDate }.Max().Add(_interval);
} }
if (DateTime.UtcNow > triggerDate) if (DateTime.UtcNow > triggerDate)
@ -73,7 +72,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
dueTime = maxDueTime; dueTime = maxDueTime;
} }
Timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1)); _timer = new Timer(state => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
} }
/// <summary> /// <summary>
@ -89,10 +88,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary> /// </summary>
private void DisposeTimer() private void DisposeTimer()
{ {
if (Timer != null) _timer?.Dispose();
{
Timer.Dispose();
}
} }
/// <summary> /// <summary>

@ -1,5 +1,3 @@
#nullable disable
#pragma warning disable CS1591 #pragma warning disable CS1591
using System; using System;
@ -12,24 +10,28 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <summary> /// <summary>
/// Class StartupTaskTrigger. /// Class StartupTaskTrigger.
/// </summary> /// </summary>
public class StartupTrigger : ITaskTrigger public sealed class StartupTrigger : ITaskTrigger
{ {
public const int DelayMs = 3000;
/// <summary> /// <summary>
/// Occurs when [triggered]. /// Initializes a new instance of the <see cref="StartupTrigger"/> class.
/// </summary> /// </summary>
public event EventHandler<EventArgs> Triggered; /// <param name="taskOptions">The options of this task.</param>
public StartupTrigger(TaskOptions taskOptions)
public int DelayMs { get; set; } {
TaskOptions = taskOptions;
}
/// <summary> /// <summary>
/// Gets or sets the options of this task. /// Occurs when [triggered].
/// </summary> /// </summary>
public TaskOptions TaskOptions { get; set; } public event EventHandler<EventArgs>? Triggered;
public StartupTrigger() /// <summary>
{ /// Gets the options of this task.
DelayMs = 3000; /// </summary>
} public TaskOptions TaskOptions { get; }
/// <summary> /// <summary>
/// Stars waiting for the trigger action. /// Stars waiting for the trigger action.

@ -1,5 +1,3 @@
#nullable disable
using System; using System;
using System.Threading; using System.Threading;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
@ -10,35 +8,34 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <summary> /// <summary>
/// Represents a task trigger that fires on a weekly basis. /// Represents a task trigger that fires on a weekly basis.
/// </summary> /// </summary>
public class WeeklyTrigger : ITaskTrigger public sealed class WeeklyTrigger : ITaskTrigger
{ {
/// <summary> private readonly TimeSpan _timeOfDay;
/// Occurs when [triggered]. private readonly DayOfWeek _dayOfWeek;
/// </summary> private Timer? _timer;
public event EventHandler<EventArgs> Triggered;
/// <summary>
/// Gets or sets the time of day to trigger the task to run.
/// </summary>
/// <value>The time of day.</value>
public TimeSpan TimeOfDay { get; set; }
/// <summary> /// <summary>
/// Gets or sets the day of week. /// Initializes a new instance of the <see cref="WeeklyTrigger"/> class.
/// </summary> /// </summary>
/// <value>The day of week.</value> /// <param name="timeofDay">The time of day to trigger the task to run.</param>
public DayOfWeek DayOfWeek { get; set; } /// <param name="dayOfWeek">The day of week.</param>
/// <param name="taskOptions">The options of this task.</param>
public WeeklyTrigger(TimeSpan timeofDay, DayOfWeek dayOfWeek, TaskOptions taskOptions)
{
_timeOfDay = timeofDay;
_dayOfWeek = dayOfWeek;
TaskOptions = taskOptions;
}
/// <summary> /// <summary>
/// Gets or sets the options of this task. /// Occurs when [triggered].
/// </summary> /// </summary>
public TaskOptions TaskOptions { get; set; } public event EventHandler<EventArgs>? Triggered;
/// <summary> /// <summary>
/// Gets or sets the timer. /// Gets the options of this task.
/// </summary> /// </summary>
/// <value>The timer.</value> public TaskOptions TaskOptions { get; }
private Timer Timer { get; set; }
/// <summary> /// <summary>
/// Stars waiting for the trigger action. /// Stars waiting for the trigger action.
@ -53,7 +50,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
var triggerDate = GetNextTriggerDateTime(); var triggerDate = GetNextTriggerDateTime();
Timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1)); _timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
} }
/// <summary> /// <summary>
@ -65,22 +62,22 @@ namespace Emby.Server.Implementations.ScheduledTasks
var now = DateTime.Now; var now = DateTime.Now;
// If it's on the same day // If it's on the same day
if (now.DayOfWeek == DayOfWeek) if (now.DayOfWeek == _dayOfWeek)
{ {
// It's either later today, or a week from now // It's either later today, or a week from now
return now.TimeOfDay < TimeOfDay ? now.Date.Add(TimeOfDay) : now.Date.AddDays(7).Add(TimeOfDay); return now.TimeOfDay < _timeOfDay ? now.Date.Add(_timeOfDay) : now.Date.AddDays(7).Add(_timeOfDay);
} }
var triggerDate = now.Date; var triggerDate = now.Date;
// Walk the date forward until we get to the trigger day // Walk the date forward until we get to the trigger day
while (triggerDate.DayOfWeek != DayOfWeek) while (triggerDate.DayOfWeek != _dayOfWeek)
{ {
triggerDate = triggerDate.AddDays(1); triggerDate = triggerDate.AddDays(1);
} }
// Return the trigger date plus the time offset // Return the trigger date plus the time offset
return triggerDate.Add(TimeOfDay); return triggerDate.Add(_timeOfDay);
} }
/// <summary> /// <summary>
@ -96,10 +93,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// </summary> /// </summary>
private void DisposeTimer() private void DisposeTimer()
{ {
if (Timer != null) _timer?.Dispose();
{
Timer.Dispose();
}
} }
/// <summary> /// <summary>

@ -1,5 +1,4 @@
#pragma warning disable CS1591 #pragma warning disable CS1591
#pragma warning disable SA1600
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;

@ -1,5 +1,3 @@
#nullable disable
using System; using System;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
@ -19,6 +17,11 @@ namespace Emby.Server.Implementations.Udp
/// </summary> /// </summary>
public sealed class UdpServer : IDisposable public sealed class UdpServer : IDisposable
{ {
/// <summary>
/// Address Override Configuration Key.
/// </summary>
public const string AddressOverrideConfigKey = "PublishedServerUrl";
/// <summary> /// <summary>
/// The _logger. /// The _logger.
/// </summary> /// </summary>
@ -26,11 +29,6 @@ namespace Emby.Server.Implementations.Udp
private readonly IServerApplicationHost _appHost; private readonly IServerApplicationHost _appHost;
private readonly IConfiguration _config; private readonly IConfiguration _config;
/// <summary>
/// Address Override Configuration Key.
/// </summary>
public const string AddressOverrideConfigKey = "PublishedServerUrl";
private Socket _udpSocket; private Socket _udpSocket;
private IPEndPoint _endpoint; private IPEndPoint _endpoint;
private readonly byte[] _receiveBuffer = new byte[8192]; private readonly byte[] _receiveBuffer = new byte[8192];
@ -40,49 +38,58 @@ namespace Emby.Server.Implementations.Udp
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="UdpServer" /> class. /// Initializes a new instance of the <see cref="UdpServer" /> class.
/// </summary> /// </summary>
public UdpServer(ILogger logger, IServerApplicationHost appHost, IConfiguration configuration) /// <param name="logger">The logger.</param>
/// <param name="appHost">The application host.</param>
/// <param name="configuration">The configuration manager.</param>
/// <param name="port">The port.</param>
public UdpServer(
ILogger logger,
IServerApplicationHost appHost,
IConfiguration configuration,
int port)
{ {
_logger = logger; _logger = logger;
_appHost = appHost; _appHost = appHost;
_config = configuration; _config = configuration;
_endpoint = new IPEndPoint(IPAddress.Any, port);
_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
} }
private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken) private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken)
{ {
string localUrl = !string.IsNullOrEmpty(_config[AddressOverrideConfigKey]) string? localUrl = _config[AddressOverrideConfigKey];
? _config[AddressOverrideConfigKey] if (string.IsNullOrEmpty(localUrl))
: _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address); {
localUrl = _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address);
}
if (!string.IsNullOrEmpty(localUrl)) if (string.IsNullOrEmpty(localUrl))
{ {
var response = new ServerDiscoveryInfo(localUrl, _appHost.SystemId, _appHost.FriendlyName); _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
return;
}
try var response = new ServerDiscoveryInfo(localUrl, _appHost.SystemId, _appHost.FriendlyName);
{
await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false); try
} {
catch (SocketException ex) await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
{
_logger.LogError(ex, "Error sending response message");
}
} }
else catch (SocketException ex)
{ {
_logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined."); _logger.LogError(ex, "Error sending response message");
} }
} }
/// <summary> /// <summary>
/// Starts the specified port. /// Starts the specified port.
/// </summary> /// </summary>
/// <param name="port">The port.</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
public void Start(int port, CancellationToken cancellationToken) public void Start(CancellationToken cancellationToken)
{ {
_endpoint = new IPEndPoint(IPAddress.Any, port);
_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_udpSocket.Bind(_endpoint); _udpSocket.Bind(_endpoint);
_ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
@ -90,9 +97,9 @@ namespace Emby.Server.Implementations.Udp
private async Task BeginReceiveAsync(CancellationToken cancellationToken) private async Task BeginReceiveAsync(CancellationToken cancellationToken)
{ {
var infiniteTask = Task.Delay(-1, cancellationToken);
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
var infiniteTask = Task.Delay(-1, cancellationToken);
try try
{ {
var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint); var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);

@ -43,7 +43,12 @@ namespace Jellyfin.Server.Implementations.Events
private async Task PublishInternal<T>(T eventArgs) private async Task PublishInternal<T>(T eventArgs)
where T : EventArgs where T : EventArgs
{ {
using var scope = _appHost.ServiceProvider.CreateScope(); using var scope = _appHost.ServiceProvider?.CreateScope();
if (scope == null)
{
return;
}
foreach (var service in scope.ServiceProvider.GetServices<IEventConsumer<T>>()) foreach (var service in scope.ServiceProvider.GetServices<IEventConsumer<T>>())
{ {
try try

@ -1,5 +1,3 @@
#nullable disable
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
@ -12,7 +10,7 @@ namespace MediaBrowser.Common
/// </summary> /// </summary>
/// <param name="type">Type to create.</param> /// <param name="type">Type to create.</param>
/// <returns>New instance of type <param>type</param>.</returns> /// <returns>New instance of type <param>type</param>.</returns>
public delegate object CreationDelegateFactory(Type type); public delegate object? CreationDelegateFactory(Type type);
/// <summary> /// <summary>
/// An interface to be implemented by the applications hosting a kernel. /// An interface to be implemented by the applications hosting a kernel.
@ -22,7 +20,7 @@ namespace MediaBrowser.Common
/// <summary> /// <summary>
/// Occurs when [has pending restart changed]. /// Occurs when [has pending restart changed].
/// </summary> /// </summary>
event EventHandler HasPendingRestartChanged; event EventHandler? HasPendingRestartChanged;
/// <summary> /// <summary>
/// Gets the name. /// Gets the name.
@ -63,7 +61,7 @@ namespace MediaBrowser.Common
/// <summary> /// <summary>
/// Gets or sets the service provider. /// Gets or sets the service provider.
/// </summary> /// </summary>
IServiceProvider ServiceProvider { get; set; } IServiceProvider? ServiceProvider { get; set; }
/// <summary> /// <summary>
/// Gets the application version. /// Gets the application version.

@ -1,9 +0,0 @@
#pragma warning disable CS1591
namespace MediaBrowser.MediaEncoding.Subtitles
{
public static class ParserValues
{
public const string NewLine = "\r\n";
}
}

@ -14,9 +14,9 @@ namespace MediaBrowser.Model.Tasks
event EventHandler<EventArgs>? Triggered; event EventHandler<EventArgs>? Triggered;
/// <summary> /// <summary>
/// Gets or sets the options of this task. /// Gets the options of this task.
/// </summary> /// </summary>
TaskOptions TaskOptions { get; set; } TaskOptions TaskOptions { get; }
/// <summary> /// <summary>
/// Stars waiting for the trigger action. /// Stars waiting for the trigger action.

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Rules for Jellyfin.Server" Description="Code analysis rules for Jellyfin.Server.csproj" ToolsVersion="14.0"> <RuleSet Name="Rules for Jellyfin.Server" Description="Code analysis rules for Jellyfin.Server.csproj" ToolsVersion="14.0">
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers"> <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<!-- disable warning CA1040: Avoid empty interfaces -->
<Rule Id="CA1040" Action="Info" />
<!-- disable warning SA1009: Closing parenthesis should be followed by a space. --> <!-- disable warning SA1009: Closing parenthesis should be followed by a space. -->
<Rule Id="SA1009" Action="None" /> <Rule Id="SA1009" Action="None" />
<!-- disable warning SA1011: Closing square bracket should be followed by a space. --> <!-- disable warning SA1011: Closing square bracket should be followed by a space. -->

Loading…
Cancel
Save