More cleanup

This commit is contained in:
Bond_009 2021-12-15 18:25:36 +01:00 committed by Cody Robibero (Rebase PR Action)
parent 4441513ca4
commit ea8f40e84a
46 changed files with 135 additions and 203 deletions

View File

@ -17,8 +17,7 @@ namespace Emby.Dlna.Didl
public Filter(string filter) public Filter(string filter)
{ {
_all = string.Equals(filter, "*", StringComparison.OrdinalIgnoreCase); _all = string.Equals(filter, "*", StringComparison.OrdinalIgnoreCase);
_fields = filter.Split(',', StringSplitOptions.RemoveEmptyEntries);
_fields = (filter ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries);
} }
public bool Contains(string field) public bool Contains(string field)

View File

@ -1179,6 +1179,7 @@ namespace Emby.Dlna.PlayTo
return new Device(deviceProperties, httpClientFactory, logger); return new Device(deviceProperties, httpClientFactory, logger);
} }
#nullable enable
private static DeviceIcon CreateIcon(XElement element) private static DeviceIcon CreateIcon(XElement element)
{ {
if (element == null) if (element == null)
@ -1186,69 +1187,61 @@ namespace Emby.Dlna.PlayTo
throw new ArgumentNullException(nameof(element)); throw new ArgumentNullException(nameof(element));
} }
var mimeType = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("mimetype"));
var width = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("width")); var width = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("width"));
var height = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("height")); var height = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("height"));
var depth = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("depth"));
var url = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("url"));
var widthValue = int.Parse(width, NumberStyles.Integer, CultureInfo.InvariantCulture); _ = int.TryParse(width, NumberStyles.Integer, CultureInfo.InvariantCulture, out var widthValue);
var heightValue = int.Parse(height, NumberStyles.Integer, CultureInfo.InvariantCulture); _ = int.TryParse(height, NumberStyles.Integer, CultureInfo.InvariantCulture, out var heightValue);
return new DeviceIcon return new DeviceIcon
{ {
Depth = depth, Depth = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("depth")) ?? string.Empty,
Height = heightValue, Height = heightValue,
MimeType = mimeType, MimeType = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("mimetype")) ?? string.Empty,
Url = url, Url = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("url")) ?? string.Empty,
Width = widthValue Width = widthValue
}; };
} }
private static DeviceService Create(XElement element) private static DeviceService Create(XElement element)
=> new DeviceService()
{ {
var type = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceType")); ControlUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("controlURL")) ?? string.Empty,
var id = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceId")); EventSubUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("eventSubURL")) ?? string.Empty,
var scpdUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("SCPDURL")); ScpdUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("SCPDURL")) ?? string.Empty,
var controlURL = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("controlURL")); ServiceId = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceId")) ?? string.Empty,
var eventSubURL = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("eventSubURL")); ServiceType = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceType")) ?? string.Empty
return new DeviceService
{
ControlUrl = controlURL,
EventSubUrl = eventSubURL,
ScpdUrl = scpdUrl,
ServiceId = id,
ServiceType = type
}; };
}
private void UpdateMediaInfo(UBaseObject mediaInfo, TransportState state) private void UpdateMediaInfo(UBaseObject? mediaInfo, TransportState state)
{ {
TransportState = state; TransportState = state;
var previousMediaInfo = CurrentMediaInfo; var previousMediaInfo = CurrentMediaInfo;
CurrentMediaInfo = mediaInfo; CurrentMediaInfo = mediaInfo;
if (previousMediaInfo == null && mediaInfo != null) if (mediaInfo == null)
{
if (previousMediaInfo != null)
{
OnPlaybackStop(previousMediaInfo);
}
}
else if (previousMediaInfo == null)
{ {
if (state != TransportState.Stopped) if (state != TransportState.Stopped)
{ {
OnPlaybackStart(mediaInfo); OnPlaybackStart(mediaInfo);
} }
} }
else if (mediaInfo != null && previousMediaInfo != null && !mediaInfo.Equals(previousMediaInfo)) else if (mediaInfo.Equals(previousMediaInfo))
{
OnMediaChanged(previousMediaInfo, mediaInfo);
}
else if (mediaInfo == null && previousMediaInfo != null)
{
OnPlaybackStop(previousMediaInfo);
}
else if (mediaInfo != null && mediaInfo.Equals(previousMediaInfo))
{ {
OnPlaybackProgress(mediaInfo); OnPlaybackProgress(mediaInfo);
} }
else
{
OnMediaChanged(previousMediaInfo, mediaInfo);
}
} }
private void OnPlaybackStart(UBaseObject mediaInfo) private void OnPlaybackStart(UBaseObject mediaInfo)

View File

@ -210,9 +210,9 @@ namespace Emby.Dlna.PlayTo
var mediaSource = await streamInfo.GetMediaSource(CancellationToken.None).ConfigureAwait(false); var mediaSource = await streamInfo.GetMediaSource(CancellationToken.None).ConfigureAwait(false);
var duration = mediaSource == null ? var duration = mediaSource == null
(_device.Duration == null ? (long?)null : _device.Duration.Value.Ticks) : ? _device.Duration?.Ticks
mediaSource.RunTimeTicks; : mediaSource.RunTimeTicks;
var playedToCompletion = positionTicks.HasValue && positionTicks.Value == 0; var playedToCompletion = positionTicks.HasValue && positionTicks.Value == 0;

View File

@ -175,7 +175,7 @@ namespace Emby.Dlna.PlayTo
var sendValue = state.AllowedValues.FirstOrDefault(a => string.Equals(a, commandParameter, StringComparison.OrdinalIgnoreCase)) ?? var sendValue = state.AllowedValues.FirstOrDefault(a => string.Equals(a, commandParameter, StringComparison.OrdinalIgnoreCase)) ??
(state.AllowedValues.Count > 0 ? state.AllowedValues[0] : value); (state.AllowedValues.Count > 0 ? state.AllowedValues[0] : value);
return string.Format(CultureInfo.InvariantCulture, "<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}</{0}>", argument.Name, state.DataType ?? "string", sendValue); return string.Format(CultureInfo.InvariantCulture, "<{0} xmlns:dt=\"urn:schemas-microsoft-com:datatypes\" dt:dt=\"{1}\">{2}</{0}>", argument.Name, state.DataType, sendValue);
} }
return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}</{0}>", argument.Name, value); return string.Format(CultureInfo.InvariantCulture, "<{0}>{1}</{0}>", argument.Name, value);

View File

@ -167,8 +167,7 @@ namespace Emby.Dlna.Profiles
public void AddXmlRootAttribute(string name, string value) public void AddXmlRootAttribute(string name, string value)
{ {
var atts = XmlRootAttributes ?? System.Array.Empty<XmlAttribute>(); var list = XmlRootAttributes.ToList();
var list = atts.ToList();
list.Add(new XmlAttribute list.Add(new XmlAttribute
{ {

View File

@ -189,7 +189,7 @@ namespace Emby.Dlna.Server
builder.Append("<icon>"); builder.Append("<icon>");
builder.Append("<mimetype>") builder.Append("<mimetype>")
.Append(SecurityElement.Escape(icon.MimeType ?? string.Empty)) .Append(SecurityElement.Escape(icon.MimeType))
.Append("</mimetype>"); .Append("</mimetype>");
builder.Append("<width>") builder.Append("<width>")
.Append(SecurityElement.Escape(icon.Width.ToString(CultureInfo.InvariantCulture))) .Append(SecurityElement.Escape(icon.Width.ToString(CultureInfo.InvariantCulture)))
@ -198,7 +198,7 @@ namespace Emby.Dlna.Server
.Append(SecurityElement.Escape(icon.Height.ToString(CultureInfo.InvariantCulture))) .Append(SecurityElement.Escape(icon.Height.ToString(CultureInfo.InvariantCulture)))
.Append("</height>"); .Append("</height>");
builder.Append("<depth>") builder.Append("<depth>")
.Append(SecurityElement.Escape(icon.Depth ?? string.Empty)) .Append(SecurityElement.Escape(icon.Depth))
.Append("</depth>"); .Append("</depth>");
builder.Append("<url>") builder.Append("<url>")
.Append(BuildUrl(icon.Url)) .Append(BuildUrl(icon.Url))
@ -219,10 +219,10 @@ namespace Emby.Dlna.Server
builder.Append("<service>"); builder.Append("<service>");
builder.Append("<serviceType>") builder.Append("<serviceType>")
.Append(SecurityElement.Escape(service.ServiceType ?? string.Empty)) .Append(SecurityElement.Escape(service.ServiceType))
.Append("</serviceType>"); .Append("</serviceType>");
builder.Append("<serviceId>") builder.Append("<serviceId>")
.Append(SecurityElement.Escape(service.ServiceId ?? string.Empty)) .Append(SecurityElement.Escape(service.ServiceId))
.Append("</serviceId>"); .Append("</serviceId>");
builder.Append("<SCPDURL>") builder.Append("<SCPDURL>")
.Append(BuildUrl(service.ScpdUrl)) .Append(BuildUrl(service.ScpdUrl))

View File

@ -38,7 +38,7 @@ namespace Emby.Dlna.Service
builder.Append("<action>"); builder.Append("<action>");
builder.Append("<name>") builder.Append("<name>")
.Append(SecurityElement.Escape(item.Name ?? string.Empty)) .Append(SecurityElement.Escape(item.Name))
.Append("</name>"); .Append("</name>");
builder.Append("<argumentList>"); builder.Append("<argumentList>");
@ -48,13 +48,13 @@ namespace Emby.Dlna.Service
builder.Append("<argument>"); builder.Append("<argument>");
builder.Append("<name>") builder.Append("<name>")
.Append(SecurityElement.Escape(argument.Name ?? string.Empty)) .Append(SecurityElement.Escape(argument.Name))
.Append("</name>"); .Append("</name>");
builder.Append("<direction>") builder.Append("<direction>")
.Append(SecurityElement.Escape(argument.Direction ?? string.Empty)) .Append(SecurityElement.Escape(argument.Direction))
.Append("</direction>"); .Append("</direction>");
builder.Append("<relatedStateVariable>") builder.Append("<relatedStateVariable>")
.Append(SecurityElement.Escape(argument.RelatedStateVariable ?? string.Empty)) .Append(SecurityElement.Escape(argument.RelatedStateVariable))
.Append("</relatedStateVariable>"); .Append("</relatedStateVariable>");
builder.Append("</argument>"); builder.Append("</argument>");
@ -81,10 +81,10 @@ namespace Emby.Dlna.Service
.Append("\">"); .Append("\">");
builder.Append("<name>") builder.Append("<name>")
.Append(SecurityElement.Escape(item.Name ?? string.Empty)) .Append(SecurityElement.Escape(item.Name))
.Append("</name>"); .Append("</name>");
builder.Append("<dataType>") builder.Append("<dataType>")
.Append(SecurityElement.Escape(item.DataType ?? string.Empty)) .Append(SecurityElement.Escape(item.DataType))
.Append("</dataType>"); .Append("</dataType>");
if (item.AllowedValues.Count > 0) if (item.AllowedValues.Count > 0)

View File

@ -242,7 +242,7 @@ namespace Emby.Drawing
return ImageFormat.Jpg; return ImageFormat.Jpg;
} }
private string? GetMimeType(ImageFormat format, string path) private string GetMimeType(ImageFormat format, string path)
=> format switch => format switch
{ {
ImageFormat.Bmp => MimeTypes.GetMimeType("i.bmp"), ImageFormat.Bmp => MimeTypes.GetMimeType("i.bmp"),

View File

@ -50,7 +50,7 @@ namespace Emby.Naming.TV
if (expression.IsNamed) if (expression.IsNamed)
{ {
result.SeriesName = match.Groups["seriesname"].Value; result.SeriesName = match.Groups["seriesname"].Value;
result.Success = !string.IsNullOrEmpty(result.SeriesName) && !string.IsNullOrEmpty(match.Groups["seasonnumber"]?.Value); result.Success = !string.IsNullOrEmpty(result.SeriesName) && !match.Groups["seasonnumber"].ValueSpan.IsEmpty;
} }
} }

View File

@ -24,63 +24,63 @@ namespace Emby.Notifications
{ {
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.ApplicationUpdateInstalled.ToString() Type = nameof(NotificationType.ApplicationUpdateInstalled)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.InstallationFailed.ToString() Type = nameof(NotificationType.InstallationFailed)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.PluginInstalled.ToString() Type = nameof(NotificationType.PluginInstalled)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.PluginError.ToString() Type = nameof(NotificationType.PluginError)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.PluginUninstalled.ToString() Type = nameof(NotificationType.PluginUninstalled)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.PluginUpdateInstalled.ToString() Type = nameof(NotificationType.PluginUpdateInstalled)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.ServerRestartRequired.ToString() Type = nameof(NotificationType.ServerRestartRequired)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.TaskFailed.ToString() Type = nameof(NotificationType.TaskFailed)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.NewLibraryContent.ToString() Type = nameof(NotificationType.NewLibraryContent)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.AudioPlayback.ToString() Type = nameof(NotificationType.AudioPlayback)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.VideoPlayback.ToString() Type = nameof(NotificationType.VideoPlayback)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.AudioPlaybackStopped.ToString() Type = nameof(NotificationType.AudioPlaybackStopped)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.VideoPlaybackStopped.ToString() Type = nameof(NotificationType.VideoPlaybackStopped)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.UserLockedOut.ToString() Type = nameof(NotificationType.UserLockedOut)
}, },
new NotificationTypeInfo new NotificationTypeInfo
{ {
Type = NotificationType.ApplicationUpdateAvailable.ToString() Type = nameof(NotificationType.ApplicationUpdateAvailable)
} }
}; };
@ -98,7 +98,7 @@ namespace Emby.Notifications
private void Update(NotificationTypeInfo note) private void Update(NotificationTypeInfo note)
{ {
note.Name = _localization.GetLocalizedString("NotificationOption" + note.Type) ?? note.Type; note.Name = _localization.GetLocalizedString("NotificationOption" + note.Type);
note.IsBasedOnUserEvent = note.Type.IndexOf("Playback", StringComparison.OrdinalIgnoreCase) != -1; note.IsBasedOnUserEvent = note.Type.IndexOf("Playback", StringComparison.OrdinalIgnoreCase) != -1;

View File

@ -371,7 +371,7 @@ namespace Emby.Server.Implementations.AppBase
NewConfiguration = configuration NewConfiguration = configuration
}); });
_configurations.AddOrUpdate(key, configuration, (k, v) => configuration); _configurations.AddOrUpdate(key, configuration, (_, _) => configuration);
var path = GetConfigurationFile(key); var path = GetConfigurationFile(key);
Directory.CreateDirectory(Path.GetDirectoryName(path)); Directory.CreateDirectory(Path.GetDirectoryName(path));

View File

@ -282,8 +282,6 @@ namespace Emby.Server.Implementations.Data
typeof(AggregateFolder) typeof(AggregateFolder)
}; };
private readonly Dictionary<string, string> _types = GetTypeMapDictionary();
private static readonly Dictionary<BaseItemKind, string> _baseItemKindNames = new() private static readonly Dictionary<BaseItemKind, string> _baseItemKindNames = new()
{ {
{ BaseItemKind.AggregateFolder, typeof(AggregateFolder).FullName }, { BaseItemKind.AggregateFolder, typeof(AggregateFolder).FullName },
@ -3440,11 +3438,6 @@ namespace Emby.Server.Implementations.Data
return true; return true;
} }
private bool IsValidType(string value)
{
return IsAlphaNumeric(value);
}
private bool IsValidMediaType(string value) private bool IsValidMediaType(string value)
{ {
return IsAlphaNumeric(value); return IsAlphaNumeric(value);
@ -4711,7 +4704,7 @@ namespace Emby.Server.Implementations.Data
if (statement == null) if (statement == null)
{ {
int index = 0; int index = 0;
string excludedTags = string.Join(',', query.ExcludeInheritedTags.Select(t => paramName + index++)); string excludedTags = string.Join(',', query.ExcludeInheritedTags.Select(_ => paramName + index++));
whereClauses.Add("((select CleanValue from itemvalues where ItemId=Guid and Type=6 and cleanvalue in (" + excludedTags + ")) is null)"); whereClauses.Add("((select CleanValue from itemvalues where ItemId=Guid and Type=6 and cleanvalue in (" + excludedTags + ")) is null)");
} }
else else
@ -4968,21 +4961,6 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
} }
} }
private static Dictionary<string, string> GetTypeMapDictionary()
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var t in _knownTypes)
{
dict[t.Name] = t.FullName;
}
dict["Program"] = typeof(LiveTvProgram).FullName;
dict["TvChannel"] = typeof(LiveTvChannel).FullName;
return dict;
}
public void DeleteItem(Guid id) public void DeleteItem(Guid id)
{ {
if (id == Guid.Empty) if (id == Guid.Empty)

View File

@ -37,7 +37,7 @@ namespace Emby.Server.Implementations.Devices
{ {
var value = File.ReadAllText(CachePath, Encoding.UTF8); var value = File.ReadAllText(CachePath, Encoding.UTF8);
if (Guid.TryParse(value, out var guid)) if (Guid.TryParse(value, out _))
{ {
return value; return value;
} }

View File

@ -109,7 +109,7 @@ namespace Emby.Server.Implementations.Dto
} }
}); });
SetItemByNameInfo(item, dto, libraryItems, user); SetItemByNameInfo(item, dto, libraryItems);
} }
} }
@ -153,8 +153,7 @@ namespace Emby.Server.Implementations.Dto
new DtoOptions(false) new DtoOptions(false)
{ {
EnableImages = false EnableImages = false
}), }));
user);
} }
return dto; return dto;
@ -311,13 +310,13 @@ namespace Emby.Server.Implementations.Dto
if (taggedItems != null && options.ContainsField(ItemFields.ItemCounts)) if (taggedItems != null && options.ContainsField(ItemFields.ItemCounts))
{ {
SetItemByNameInfo(item, dto, taggedItems, user); SetItemByNameInfo(item, dto, taggedItems);
} }
return dto; return dto;
} }
private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IList<BaseItem> taggedItems, User user = null) private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IList<BaseItem> taggedItems)
{ {
if (item is MusicArtist) if (item is MusicArtist)
{ {

View File

@ -101,7 +101,7 @@ namespace Emby.Server.Implementations.EntryPoints
} }
} }
_lastProgressMessageTimes.AddOrUpdate(item.Id, key => DateTime.UtcNow, (key, existing) => DateTime.UtcNow); _lastProgressMessageTimes.AddOrUpdate(item.Id, _ => DateTime.UtcNow, (_, _) => DateTime.UtcNow);
var dict = new Dictionary<string, string>(); var dict = new Dictionary<string, string>();
dict["ItemId"] = item.Id.ToString("N", CultureInfo.InvariantCulture); dict["ItemId"] = item.Id.ToString("N", CultureInfo.InvariantCulture);
@ -144,7 +144,7 @@ namespace Emby.Server.Implementations.EntryPoints
{ {
OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 100))); OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 100)));
_lastProgressMessageTimes.TryRemove(e.Argument.Id, out DateTime removed); _lastProgressMessageTimes.TryRemove(e.Argument.Id, out _);
} }
private static bool EnableRefreshMessage(BaseItem item) private static bool EnableRefreshMessage(BaseItem item)
@ -423,7 +423,6 @@ namespace Emby.Server.Implementations.EntryPoints
continue; continue;
} }
var collectionFolders = _libraryManager.GetCollectionFolders(item, allUserRootChildren);
foreach (var folder in allUserRootChildren) foreach (var folder in allUserRootChildren)
{ {
list.Add(folder.Id.ToString("N", CultureInfo.InvariantCulture)); list.Add(folder.Id.ToString("N", CultureInfo.InvariantCulture));

View File

@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.EntryPoints
var changes = _changedItems.ToList(); var changes = _changedItems.ToList();
_changedItems.Clear(); _changedItems.Clear();
var task = SendNotifications(changes, CancellationToken.None); SendNotifications(changes, CancellationToken.None).GetAwaiter().GetResult();
if (_updateTimer != null) if (_updateTimer != null)
{ {

View File

@ -47,7 +47,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
{ {
var session = await GetSession(requestContext).ConfigureAwait(false); var session = await GetSession(requestContext).ConfigureAwait(false);
return session == null || session.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(session.UserId); return session.UserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(session.UserId);
} }
public Task<User?> GetUser(object requestContext) public Task<User?> GetUser(object requestContext)

View File

@ -217,8 +217,13 @@ namespace Emby.Server.Implementations.IO
/// <inheritdoc /> /// <inheritdoc />
public void Dispose() public void Dispose()
{ {
_disposed = true; if (_disposed)
{
return;
}
DisposeTimer(); DisposeTimer();
_disposed = true;
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
} }

View File

@ -99,7 +99,7 @@ namespace Emby.Server.Implementations.IO
// But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
await Task.Delay(45000).ConfigureAwait(false); await Task.Delay(45000).ConfigureAwait(false);
_tempIgnoredPaths.TryRemove(path, out var val); _tempIgnoredPaths.TryRemove(path, out _);
if (refreshPath) if (refreshPath)
{ {

View File

@ -544,16 +544,6 @@ namespace Emby.Server.Implementations.IO
/// <inheritdoc /> /// <inheritdoc />
public virtual bool AreEqual(string path1, string path2) public virtual bool AreEqual(string path1, string path2)
{ {
if (path1 == null && path2 == null)
{
return true;
}
if (path1 == null || path2 == null)
{
return false;
}
return string.Equals( return string.Equals(
NormalizePath(path1), NormalizePath(path1),
NormalizePath(path2), NormalizePath(path2),

View File

@ -16,7 +16,7 @@ using Emby.Naming.TV;
using Emby.Naming.Video; using Emby.Naming.Video;
using Emby.Server.Implementations.Library.Validators; using Emby.Server.Implementations.Library.Validators;
using Emby.Server.Implementations.Playlists; using Emby.Server.Implementations.Playlists;
using Emby.Server.Implementations.ScheduledTasks; using Emby.Server.Implementations.ScheduledTasks.Tasks;
using Jellyfin.Data.Entities; using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums; using Jellyfin.Data.Enums;
using Jellyfin.Extensions; using Jellyfin.Extensions;
@ -2678,7 +2678,7 @@ namespace Emby.Server.Implementations.Library
return new ItemLookupInfo return new ItemLookupInfo
{ {
Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName.ToString() : result.Name, Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name,
Year = result.Year Year = result.Year
}; };
} }

View File

@ -66,12 +66,9 @@ namespace Emby.Server.Implementations.Library
{ {
var delayMs = mediaSource.AnalyzeDurationMs ?? 0; var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
delayMs = Math.Max(3000, delayMs); delayMs = Math.Max(3000, delayMs);
if (delayMs > 0)
{
_logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs); _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs);
await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
} }
}
mediaSource.AnalyzeDurationMs = 3000; mediaSource.AnalyzeDurationMs = 3000;

View File

@ -103,7 +103,7 @@ namespace Emby.Server.Implementations.Library
public List<BaseItem> GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions) public List<BaseItem> GetInstantMixFromItem(BaseItem item, User user, DtoOptions dtoOptions)
{ {
if (item is MusicGenre genre) if (item is MusicGenre)
{ {
return GetInstantMixFromGenreIds(new[] { item.Id }, user, dtoOptions); return GetInstantMixFromGenreIds(new[] { item.Id }, user, dtoOptions);
} }

View File

@ -112,7 +112,7 @@ namespace Emby.Server.Implementations.Library.Resolvers.Audio
/// Determine if the supplied list contains what we should consider music. /// Determine if the supplied list contains what we should consider music.
/// </summary> /// </summary>
private bool ContainsMusic( private bool ContainsMusic(
IEnumerable<FileSystemMetadata> list, ICollection<FileSystemMetadata> list,
bool allowSubfolders, bool allowSubfolders,
IDirectoryService directoryService) IDirectoryService directoryService)
{ {

View File

@ -75,7 +75,7 @@ namespace Emby.Server.Implementations.Library
} }
var cacheKey = GetCacheKey(userId, item.Id); var cacheKey = GetCacheKey(userId, item.Id);
_userData.AddOrUpdate(cacheKey, userData, (k, v) => userData); _userData.AddOrUpdate(cacheKey, userData, (_, _) => userData);
UserDataSaved?.Invoke(this, new UserDataSaveEventArgs UserDataSaved?.Invoke(this, new UserDataSaveEventArgs
{ {
@ -125,7 +125,7 @@ namespace Emby.Server.Implementations.Library
var cacheKey = GetCacheKey(userId, itemId); var cacheKey = GetCacheKey(userId, itemId);
return _userData.GetOrAdd(cacheKey, k => GetUserDataInternal(userId, keys)); return _userData.GetOrAdd(cacheKey, _ => GetUserDataInternal(userId, keys));
} }
private UserItemData GetUserDataInternal(long internalUserId, List<string> keys) private UserItemData GetUserDataInternal(long internalUserId, List<string> keys)

View File

@ -173,7 +173,7 @@ namespace Emby.Server.Implementations.Library
string viewType, string viewType,
string localizationKey, string localizationKey,
string sortName, string sortName,
Jellyfin.Data.Entities.User user, User user,
string[] presetViews) string[] presetViews)
{ {
if (parents.Count == 1 && parents.All(i => string.Equals(i.CollectionType, viewType, StringComparison.OrdinalIgnoreCase))) if (parents.Count == 1 && parents.All(i => string.Equals(i.CollectionType, viewType, StringComparison.OrdinalIgnoreCase)))
@ -359,7 +359,7 @@ namespace Emby.Server.Implementations.Library
(ItemSortBy.SortName, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Descending),
(ItemSortBy.ProductionYear, SortOrder.Descending) (ItemSortBy.ProductionYear, SortOrder.Descending)
}, },
IsFolder = includeItemTypes.Length == 0 ? false : (bool?)null, IsFolder = includeItemTypes.Length == 0 ? false : null,
ExcludeItemTypes = excludeItemTypes, ExcludeItemTypes = excludeItemTypes,
IsVirtualItem = false, IsVirtualItem = false,
Limit = limit * 5, Limit = limit * 5,

View File

@ -398,7 +398,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
} }
result = new EpgChannelData(channels); result = new EpgChannelData(channels);
_epgChannels.AddOrUpdate(info.Id, result, (k, v) => result); _epgChannels.AddOrUpdate(info.Id, result, (_, _) => result);
} }
return result; return result;
@ -1248,12 +1248,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false); var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false);
var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath); var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath);
var recordingStatus = RecordingStatus.New;
string liveStreamId = null;
var channelItem = _liveTvManager.GetLiveTvChannel(timer, this); var channelItem = _liveTvManager.GetLiveTvChannel(timer, this);
string liveStreamId = null;
RecordingStatus recordingStatus;
try try
{ {
var allMediaSources = await _mediaSourceManager.GetPlaybackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false); var allMediaSources = await _mediaSourceManager.GetPlaybackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false);
@ -1339,7 +1338,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
TriggerRefresh(recordPath); TriggerRefresh(recordPath);
_libraryMonitor.ReportFileSystemChangeComplete(recordPath, false); _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
_activeRecordings.TryRemove(timer.Id, out var removed); _activeRecordings.TryRemove(timer.Id, out _);
if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10) if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
{ {
@ -1937,7 +1936,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
writer.WriteElementString("title", timer.EpisodeTitle); writer.WriteElementString("title", timer.EpisodeTitle);
} }
var premiereDate = item.PremiereDate ?? (!timer.IsRepeat ? DateTime.UtcNow : (DateTime?)null); var premiereDate = item.PremiereDate ?? (!timer.IsRepeat ? DateTime.UtcNow : null);
if (premiereDate.HasValue) if (premiereDate.HasValue)
{ {
@ -2126,12 +2125,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer) private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer)
{ {
return GetProgramInfoFromCache(timer.ProgramId, timer.ChannelId); return GetProgramInfoFromCache(timer.ProgramId);
}
private LiveTvProgram GetProgramInfoFromCache(string programId, string channelId)
{
return GetProgramInfoFromCache(programId);
} }
private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc) private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
@ -2277,7 +2271,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{ {
// Only update if not currently active - test both new timer and existing in case Id's are different // Only update if not currently active - test both new timer and existing in case Id's are different
// Id's could be different if the timer was created manually prior to series timer creation // Id's could be different if the timer was created manually prior to series timer creation
if (!_activeRecordings.TryGetValue(timer.Id, out var activeRecordingInfo) && !_activeRecordings.TryGetValue(existingTimer.Id, out activeRecordingInfo)) if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _))
{ {
UpdateExistingTimerWithNewMetadata(existingTimer, timer); UpdateExistingTimerWithNewMetadata(existingTimer, timer);
@ -2298,17 +2292,14 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
enabledTimersForSeries.Add(existingTimer); enabledTimersForSeries.Add(existingTimer);
} }
if (updateTimerSettings)
{
existingTimer.KeepUntil = seriesTimer.KeepUntil; existingTimer.KeepUntil = seriesTimer.KeepUntil;
existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired; existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired; existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds; existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds; existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
existingTimer.Priority = seriesTimer.Priority; existingTimer.Priority = seriesTimer.Priority;
}
existingTimer.SeriesTimerId = seriesTimer.Id; existingTimer.SeriesTimerId = seriesTimer.Id;
_timerProvider.Update(existingTimer); _timerProvider.Update(existingTimer);
} }
} }

View File

@ -62,12 +62,12 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
using var durationToken = new CancellationTokenSource(duration); using var durationToken = new CancellationTokenSource(duration);
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token); using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationTokenSource.Token).ConfigureAwait(false); await RecordFromFile(mediaSource, mediaSource.Path, targetFile, onStarted, cancellationTokenSource.Token).ConfigureAwait(false);
_logger.LogInformation("Recording completed to file {0}", targetFile); _logger.LogInformation("Recording completed to file {0}", targetFile);
} }
private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, Action onStarted, CancellationToken cancellationToken)
{ {
_targetPath = targetFile; _targetPath = targetFile;
Directory.CreateDirectory(Path.GetDirectoryName(targetFile)); Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
@ -81,7 +81,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
RedirectStandardInput = true, RedirectStandardInput = true,
FileName = _mediaEncoder.EncoderPath, FileName = _mediaEncoder.EncoderPath,
Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration), Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile),
WindowStyle = ProcessWindowStyle.Hidden, WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false ErrorDialog = false
@ -103,7 +103,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
StartInfo = processStartInfo, StartInfo = processStartInfo,
EnableRaisingEvents = true EnableRaisingEvents = true
}; };
_process.Exited += (sender, args) => OnFfMpegProcessExited(_process); _process.Exited += (_, _) => OnFfMpegProcessExited(_process);
_process.Start(); _process.Start();
@ -117,7 +117,7 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_logger.LogInformation("ffmpeg recording process started for {0}", _targetPath); _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
} }
private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration) private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile)
{ {
string videoArgs; string videoArgs;
if (EncodeVideo(mediaSource)) if (EncodeVideo(mediaSource))

View File

@ -159,8 +159,8 @@ namespace Emby.Server.Implementations.LiveTv.Listings
var programEntry = programDict[schedule.ProgramId]; var programEntry = programDict[schedule.ProgramId];
var allImages = images[imageIndex].Data; var allImages = images[imageIndex].Data;
var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)); var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)); var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
const double DesiredAspect = 2.0 / 3; const double DesiredAspect = 2.0 / 3;
@ -820,10 +820,5 @@ namespace Emby.Server.Implementations.LiveTv.Listings
return list; return list;
} }
private static string NormalizeName(string value)
{
return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
}
} }
} }

View File

@ -630,7 +630,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
{ {
if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound) if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
{ {
// HDHR4 doesn't have this api // HDHR4 doesn't have this api
return; return;

View File

@ -122,7 +122,6 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _)) if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
{ {
await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false); await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false);
continue;
} }
} }

View File

@ -131,7 +131,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).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false)) using (await new M3uParser(Logger, _httpClientFactory).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false))
{ {
} }
} }

View File

@ -19,7 +19,7 @@ namespace Emby.Server.Implementations.Net
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
} }
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try try
{ {
retVal.EnableBroadcast = true; retVal.EnableBroadcast = true;
@ -44,7 +44,7 @@ namespace Emby.Server.Implementations.Net
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
} }
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try try
{ {
retVal.EnableBroadcast = true; retVal.EnableBroadcast = true;
@ -85,7 +85,7 @@ namespace Emby.Server.Implementations.Net
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
} }
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try try
{ {

View File

@ -360,11 +360,6 @@ namespace Emby.Server.Implementations.Plugins
/// <inheritdoc/> /// <inheritdoc/>
public async Task<bool> GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status) public async Task<bool> GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status)
{ {
if (packageInfo == null)
{
return false;
}
var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString()); var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
var imagePath = string.Empty; var imagePath = string.Empty;
@ -617,7 +612,7 @@ namespace Emby.Server.Implementations.Plugins
if (versionIndex != -1) if (versionIndex != -1)
{ {
// Get the version number from the filename if possible. // Get the version number from the filename if possible.
metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex]; metafile = Path.GetFileName(dir[..versionIndex]);
version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion; version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
} }
else else
@ -682,7 +677,6 @@ namespace Emby.Server.Implementations.Plugins
continue; continue;
} }
var manifest = entry.Manifest;
var cleaned = false; var cleaned = false;
var path = entry.Path; var path = entry.Path;
if (_config.RemoveOldPlugins) if (_config.RemoveOldPlugins)
@ -707,12 +701,6 @@ namespace Emby.Server.Implementations.Plugins
} }
else else
{ {
if (manifest == null)
{
_logger.LogWarning("Unable to disable plugin {Path}", entry.Path);
continue;
}
ChangePluginState(entry, PluginStatus.Deleted); ChangePluginState(entry, PluginStatus.Deleted);
} }
} }

View File

@ -9,6 +9,7 @@ using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Emby.Server.Implementations.ScheduledTasks.Triggers;
using Jellyfin.Data.Events; using Jellyfin.Data.Events;
using Jellyfin.Extensions.Json; using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;

View File

@ -17,7 +17,7 @@ using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO; using MediaBrowser.Model.IO;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{ {
/// <summary> /// <summary>
/// Class ChapterImagesTask. /// Class ChapterImagesTask.

View File

@ -8,7 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{ {
/// <summary> /// <summary>
/// Class PeopleValidationTask. /// Class PeopleValidationTask.

View File

@ -12,7 +12,7 @@ using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{ {
/// <summary> /// <summary>
/// Plugin Update Task. /// Plugin Update Task.

View File

@ -9,7 +9,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Globalization; using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Tasks
{ {
/// <summary> /// <summary>
/// Class RefreshMediaLibraryTask. /// Class RefreshMediaLibraryTask.

View File

@ -3,7 +3,7 @@ using System.Threading;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Triggers
{ {
/// <summary> /// <summary>
/// Represents a task trigger that fires everyday. /// Represents a task trigger that fires everyday.
@ -41,7 +41,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param> /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param> /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup) public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{ {
DisposeTimer(); DisposeTimer();
@ -54,7 +54,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
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(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
} }
/// <summary> /// <summary>

View File

@ -4,7 +4,7 @@ using System.Threading;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Triggers
{ {
/// <summary> /// <summary>
/// Represents a task trigger that runs repeatedly on an interval. /// Represents a task trigger that runs repeatedly on an interval.
@ -43,7 +43,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param> /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param> /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup) public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{ {
DisposeTimer(); DisposeTimer();
@ -72,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(_ => OnTriggered(), null, dueTime, TimeSpan.FromMilliseconds(-1));
} }
/// <summary> /// <summary>

View File

@ -5,7 +5,7 @@ using System.Threading.Tasks;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Triggers
{ {
/// <summary> /// <summary>
/// Class StartupTaskTrigger. /// Class StartupTaskTrigger.
@ -40,7 +40,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param> /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param> /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public async void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup) public async void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{ {
if (isApplicationStartup) if (isApplicationStartup)
{ {

View File

@ -3,7 +3,7 @@ using System.Threading;
using MediaBrowser.Model.Tasks; using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.ScheduledTasks namespace Emby.Server.Implementations.ScheduledTasks.Triggers
{ {
/// <summary> /// <summary>
/// Represents a task trigger that fires on a weekly basis. /// Represents a task trigger that fires on a weekly basis.
@ -44,13 +44,13 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="taskName">The name of the task.</param> /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param> /// <param name="isApplicationStartup">if set to <c>true</c> [is application startup].</param>
public void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup) public void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup)
{ {
DisposeTimer(); DisposeTimer();
var triggerDate = GetNextTriggerDateTime(); var triggerDate = GetNextTriggerDateTime();
_timer = new Timer(state => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1)); _timer = new Timer(_ => OnTriggered(), null, triggerDate - DateTime.Now, TimeSpan.FromMilliseconds(-1));
} }
/// <summary> /// <summary>

View File

@ -33,7 +33,7 @@ namespace Emby.Server.Implementations.Sorting
/// </summary> /// </summary>
/// <param name="x">The x.</param> /// <param name="x">The x.</param>
/// <returns>System.String.</returns> /// <returns>System.String.</returns>
private static string? GetValue(BaseItem? x) private static string GetValue(BaseItem? x)
{ {
return x is Audio audio ? audio.Album : string.Empty; return x is Audio audio ? audio.Album : string.Empty;
} }

View File

@ -250,7 +250,6 @@ namespace Emby.Server.Implementations.SyncPlay
var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); var error = new GroupUpdate<string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty);
_sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None);
return;
} }
} }
} }
@ -365,7 +364,7 @@ namespace Emby.Server.Implementations.SyncPlay
{ {
var session = e.SessionInfo; var session = e.SessionInfo;
if (_sessionToGroupMap.TryGetValue(session.Id, out var group)) if (_sessionToGroupMap.TryGetValue(session.Id, out _))
{ {
var leaveGroupRequest = new LeaveGroupRequest(); var leaveGroupRequest = new LeaveGroupRequest();
LeaveGroup(session, leaveGroupRequest, CancellationToken.None); LeaveGroup(session, leaveGroupRequest, CancellationToken.None);
@ -378,7 +377,7 @@ namespace Emby.Server.Implementations.SyncPlay
var newSessionsCounter = _activeUsers.AddOrUpdate( var newSessionsCounter = _activeUsers.AddOrUpdate(
userId, userId,
1, 1,
(key, sessionsCounter) => sessionsCounter + toAdd); (_, sessionsCounter) => sessionsCounter + toAdd);
// Should never happen. // Should never happen.
if (newSessionsCounter < 0) if (newSessionsCounter < 0)

View File

@ -25,7 +25,7 @@ namespace MediaBrowser.Model.Tasks
/// <param name="logger">The <see cref="ILogger"/>.</param> /// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="taskName">The name of the task.</param> /// <param name="taskName">The name of the task.</param>
/// <param name="isApplicationStartup">Wheter or not this is is fired during startup.</param> /// <param name="isApplicationStartup">Wheter or not this is is fired during startup.</param>
void Start(TaskResult lastResult, ILogger logger, string taskName, bool isApplicationStartup); void Start(TaskResult? lastResult, ILogger logger, string taskName, bool isApplicationStartup);
/// <summary> /// <summary>
/// Stops waiting for the trigger action. /// Stops waiting for the trigger action.