Merge pull request #3390 from telans/fixes

Multiple warning fixes
pull/3394/head
Bond-009 4 years ago committed by GitHub
commit beb3896d7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -117,12 +117,19 @@ namespace DvdLib.Ifo
uint chapNum = 1; uint chapNum = 1;
vtsFs.Seek(baseAddr + offsets[titleNum], SeekOrigin.Begin); vtsFs.Seek(baseAddr + offsets[titleNum], SeekOrigin.Begin);
var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum + 1)); var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum + 1));
if (t == null) continue; if (t == null)
{
continue;
}
do do
{ {
t.Chapters.Add(new Chapter(vtsRead.ReadUInt16(), vtsRead.ReadUInt16(), chapNum)); t.Chapters.Add(new Chapter(vtsRead.ReadUInt16(), vtsRead.ReadUInt16(), chapNum));
if (titleNum + 1 < numTitles && vtsFs.Position == (baseAddr + offsets[titleNum + 1])) break; if (titleNum + 1 < numTitles && vtsFs.Position == (baseAddr + offsets[titleNum + 1]))
{
break;
}
chapNum++; chapNum++;
} }
while (vtsFs.Position < (baseAddr + endaddr)); while (vtsFs.Position < (baseAddr + endaddr));
@ -147,7 +154,10 @@ namespace DvdLib.Ifo
uint vtsPgcOffset = vtsRead.ReadUInt32(); uint vtsPgcOffset = vtsRead.ReadUInt32();
var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum)); var t = Titles.FirstOrDefault(vtst => vtst.IsVTSTitle(vtsNum, titleNum));
if (t != null) t.AddPgc(vtsRead, startByte + vtsPgcOffset, entryPgc, pgcNum); if (t != null)
{
t.AddPgc(vtsRead, startByte + vtsPgcOffset, entryPgc, pgcNum);
}
} }
} }
} }

@ -15,8 +15,14 @@ namespace DvdLib.Ifo
Second = GetBCDValue(data[2]); Second = GetBCDValue(data[2]);
Frames = GetBCDValue((byte)(data[3] & 0x3F)); Frames = GetBCDValue((byte)(data[3] & 0x3F));
if ((data[3] & 0x80) != 0) FrameRate = 30; if ((data[3] & 0x80) != 0)
else if ((data[3] & 0x40) != 0) FrameRate = 25; {
FrameRate = 30;
}
else if ((data[3] & 0x40) != 0)
{
FrameRate = 25;
}
} }
private static byte GetBCDValue(byte data) private static byte GetBCDValue(byte data)

@ -75,8 +75,15 @@ namespace DvdLib.Ifo
StillTime = br.ReadByte(); StillTime = br.ReadByte();
byte pbMode = br.ReadByte(); byte pbMode = br.ReadByte();
if (pbMode == 0) PlaybackMode = ProgramPlaybackMode.Sequential; if (pbMode == 0)
else PlaybackMode = ((pbMode & 0x80) == 0) ? ProgramPlaybackMode.Random : ProgramPlaybackMode.Shuffle; {
PlaybackMode = ProgramPlaybackMode.Sequential;
}
else
{
PlaybackMode = ((pbMode & 0x80) == 0) ? ProgramPlaybackMode.Random : ProgramPlaybackMode.Shuffle;
}
ProgramCount = (uint)(pbMode & 0x7F); ProgramCount = (uint)(pbMode & 0x7F);
Palette = br.ReadBytes(64); Palette = br.ReadBytes(64);

@ -59,7 +59,10 @@ namespace DvdLib.Ifo
var pgc = new ProgramChain(pgcNum); var pgc = new ProgramChain(pgcNum);
pgc.ParseHeader(br); pgc.ParseHeader(br);
ProgramChains.Add(pgc); ProgramChains.Add(pgc);
if (entryPgc) EntryProgramChain = pgc; if (entryPgc)
{
EntryProgramChain = pgc;
}
br.BaseStream.Seek(curPos, SeekOrigin.Begin); br.BaseStream.Seek(curPos, SeekOrigin.Begin);
} }

@ -140,55 +140,73 @@ namespace Emby.Dlna
if (!string.IsNullOrEmpty(profileInfo.DeviceDescription)) if (!string.IsNullOrEmpty(profileInfo.DeviceDescription))
{ {
if (deviceInfo.DeviceDescription == null || !IsRegexMatch(deviceInfo.DeviceDescription, profileInfo.DeviceDescription)) if (deviceInfo.DeviceDescription == null || !IsRegexMatch(deviceInfo.DeviceDescription, profileInfo.DeviceDescription))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.FriendlyName)) if (!string.IsNullOrEmpty(profileInfo.FriendlyName))
{ {
if (deviceInfo.FriendlyName == null || !IsRegexMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName)) if (deviceInfo.FriendlyName == null || !IsRegexMatch(deviceInfo.FriendlyName, profileInfo.FriendlyName))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.Manufacturer)) if (!string.IsNullOrEmpty(profileInfo.Manufacturer))
{ {
if (deviceInfo.Manufacturer == null || !IsRegexMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer)) if (deviceInfo.Manufacturer == null || !IsRegexMatch(deviceInfo.Manufacturer, profileInfo.Manufacturer))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.ManufacturerUrl)) if (!string.IsNullOrEmpty(profileInfo.ManufacturerUrl))
{ {
if (deviceInfo.ManufacturerUrl == null || !IsRegexMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl)) if (deviceInfo.ManufacturerUrl == null || !IsRegexMatch(deviceInfo.ManufacturerUrl, profileInfo.ManufacturerUrl))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.ModelDescription)) if (!string.IsNullOrEmpty(profileInfo.ModelDescription))
{ {
if (deviceInfo.ModelDescription == null || !IsRegexMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription)) if (deviceInfo.ModelDescription == null || !IsRegexMatch(deviceInfo.ModelDescription, profileInfo.ModelDescription))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.ModelName)) if (!string.IsNullOrEmpty(profileInfo.ModelName))
{ {
if (deviceInfo.ModelName == null || !IsRegexMatch(deviceInfo.ModelName, profileInfo.ModelName)) if (deviceInfo.ModelName == null || !IsRegexMatch(deviceInfo.ModelName, profileInfo.ModelName))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.ModelNumber)) if (!string.IsNullOrEmpty(profileInfo.ModelNumber))
{ {
if (deviceInfo.ModelNumber == null || !IsRegexMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber)) if (deviceInfo.ModelNumber == null || !IsRegexMatch(deviceInfo.ModelNumber, profileInfo.ModelNumber))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.ModelUrl)) if (!string.IsNullOrEmpty(profileInfo.ModelUrl))
{ {
if (deviceInfo.ModelUrl == null || !IsRegexMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl)) if (deviceInfo.ModelUrl == null || !IsRegexMatch(deviceInfo.ModelUrl, profileInfo.ModelUrl))
{
return false; return false;
}
} }
if (!string.IsNullOrEmpty(profileInfo.SerialNumber)) if (!string.IsNullOrEmpty(profileInfo.SerialNumber))
{ {
if (deviceInfo.SerialNumber == null || !IsRegexMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber)) if (deviceInfo.SerialNumber == null || !IsRegexMatch(deviceInfo.SerialNumber, profileInfo.SerialNumber))
{
return false; return false;
}
} }
return true; return true;

@ -19,8 +19,6 @@ namespace Emby.Dlna.PlayTo
{ {
public class Device : IDisposable public class Device : IDisposable
{ {
#region Fields & Properties
private Timer _timer; private Timer _timer;
public DeviceInfo Properties { get; set; } public DeviceInfo Properties { get; set; }
@ -53,10 +51,10 @@ namespace Emby.Dlna.PlayTo
public bool IsStopped => TransportState == TRANSPORTSTATE.STOPPED; public bool IsStopped => TransportState == TRANSPORTSTATE.STOPPED;
#endregion
private readonly IHttpClient _httpClient; private readonly IHttpClient _httpClient;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IServerConfigurationManager _config; private readonly IServerConfigurationManager _config;
public Action OnDeviceUnavailable { get; set; } public Action OnDeviceUnavailable { get; set; }
@ -142,8 +140,6 @@ namespace Emby.Dlna.PlayTo
} }
} }
#region Commanding
public Task VolumeDown(CancellationToken cancellationToken) public Task VolumeDown(CancellationToken cancellationToken)
{ {
var sendVolume = Math.Max(Volume - 5, 0); var sendVolume = Math.Max(Volume - 5, 0);
@ -212,7 +208,9 @@ namespace Emby.Dlna.PlayTo
var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetMute"); var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetMute");
if (command == null) if (command == null)
{
return false; return false;
}
var service = GetServiceRenderingControl(); var service = GetServiceRenderingControl();
@ -241,7 +239,9 @@ namespace Emby.Dlna.PlayTo
var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume"); var command = rendererCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume");
if (command == null) if (command == null)
{
return; return;
}
var service = GetServiceRenderingControl(); var service = GetServiceRenderingControl();
@ -264,7 +264,9 @@ namespace Emby.Dlna.PlayTo
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Seek"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Seek");
if (command == null) if (command == null)
{
return; return;
}
var service = GetAvTransportService(); var service = GetAvTransportService();
@ -289,7 +291,9 @@ namespace Emby.Dlna.PlayTo
var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI"); var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI");
if (command == null) if (command == null)
{
return; return;
}
var dictionary = new Dictionary<string, string> var dictionary = new Dictionary<string, string>
{ {
@ -402,11 +406,8 @@ namespace Emby.Dlna.PlayTo
RestartTimer(true); RestartTimer(true);
} }
#endregion
#region Get data
private int _connectFailureCount; private int _connectFailureCount;
private async void TimerCallback(object sender) private async void TimerCallback(object sender)
{ {
if (_disposed) if (_disposed)
@ -459,7 +460,9 @@ namespace Emby.Dlna.PlayTo
_connectFailureCount = 0; _connectFailureCount = 0;
if (_disposed) if (_disposed)
{
return; return;
}
// If we're not playing anything make sure we don't get data more often than neccessry to keep the Session alive // If we're not playing anything make sure we don't get data more often than neccessry to keep the Session alive
if (transportState.Value == TRANSPORTSTATE.STOPPED) if (transportState.Value == TRANSPORTSTATE.STOPPED)
@ -479,7 +482,9 @@ namespace Emby.Dlna.PlayTo
catch (Exception ex) catch (Exception ex)
{ {
if (_disposed) if (_disposed)
{
return; return;
}
_logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name); _logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name);
@ -580,7 +585,9 @@ namespace Emby.Dlna.PlayTo
cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken: cancellationToken).ConfigureAwait(false);
if (result == null || result.Document == null) if (result == null || result.Document == null)
{
return; return;
}
var valueNode = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetMuteResponse") var valueNode = result.Document.Descendants(uPnpNamespaces.RenderingControl + "GetMuteResponse")
.Select(i => i.Element("CurrentMute")) .Select(i => i.Element("CurrentMute"))
@ -870,10 +877,6 @@ namespace Emby.Dlna.PlayTo
return new string[4]; return new string[4];
} }
#endregion
#region From XML
private async Task<TransportCommands> GetAVProtocolAsync(CancellationToken cancellationToken) private async Task<TransportCommands> GetAVProtocolAsync(CancellationToken cancellationToken)
{ {
if (AvCommands != null) if (AvCommands != null)
@ -1068,8 +1071,6 @@ namespace Emby.Dlna.PlayTo
return new Device(deviceProperties, httpClient, logger, config); return new Device(deviceProperties, httpClient, logger, config);
} }
#endregion
private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
private static DeviceIcon CreateIcon(XElement element) private static DeviceIcon CreateIcon(XElement element)
{ {
@ -1193,8 +1194,6 @@ namespace Emby.Dlna.PlayTo
}); });
} }
#region IDisposable
bool _disposed; bool _disposed;
public void Dispose() public void Dispose()
@ -1221,8 +1220,6 @@ namespace Emby.Dlna.PlayTo
_disposed = true; _disposed = true;
} }
#endregion
public override string ToString() public override string ToString()
{ {
return string.Format("{0} - {1}", Properties.Name, Properties.BaseUrl); return string.Format("{0} - {1}", Properties.Name, Properties.BaseUrl);

@ -78,9 +78,15 @@ namespace Emby.Dlna.PlayTo
var info = e.Argument; var info = e.Argument;
if (!info.Headers.TryGetValue("USN", out string usn)) usn = string.Empty; if (!info.Headers.TryGetValue("USN", out string usn))
{
usn = string.Empty;
}
if (!info.Headers.TryGetValue("NT", out string nt)) nt = string.Empty; if (!info.Headers.TryGetValue("NT", out string nt))
{
nt = string.Empty;
}
string location = info.Location.ToString(); string location = info.Location.ToString();

@ -2775,22 +2775,85 @@ namespace Emby.Server.Implementations.Data
private string FixUnicodeChars(string buffer) private string FixUnicodeChars(string buffer)
{ {
if (buffer.IndexOf('\u2013') > -1) buffer = buffer.Replace('\u2013', '-'); // en dash if (buffer.IndexOf('\u2013') > -1)
if (buffer.IndexOf('\u2014') > -1) buffer = buffer.Replace('\u2014', '-'); // em dash {
if (buffer.IndexOf('\u2015') > -1) buffer = buffer.Replace('\u2015', '-'); // horizontal bar buffer = buffer.Replace('\u2013', '-'); // en dash
if (buffer.IndexOf('\u2017') > -1) buffer = buffer.Replace('\u2017', '_'); // double low line }
if (buffer.IndexOf('\u2018') > -1) buffer = buffer.Replace('\u2018', '\''); // left single quotation mark
if (buffer.IndexOf('\u2019') > -1) buffer = buffer.Replace('\u2019', '\''); // right single quotation mark if (buffer.IndexOf('\u2014') > -1)
if (buffer.IndexOf('\u201a') > -1) buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark {
if (buffer.IndexOf('\u201b') > -1) buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark buffer = buffer.Replace('\u2014', '-'); // em dash
if (buffer.IndexOf('\u201c') > -1) buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark }
if (buffer.IndexOf('\u201d') > -1) buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark
if (buffer.IndexOf('\u201e') > -1) buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark if (buffer.IndexOf('\u2015') > -1)
if (buffer.IndexOf('\u2026') > -1) buffer = buffer.Replace("\u2026", "..."); // horizontal ellipsis {
if (buffer.IndexOf('\u2032') > -1) buffer = buffer.Replace('\u2032', '\''); // prime buffer = buffer.Replace('\u2015', '-'); // horizontal bar
if (buffer.IndexOf('\u2033') > -1) buffer = buffer.Replace('\u2033', '\"'); // double prime }
if (buffer.IndexOf('\u0060') > -1) buffer = buffer.Replace('\u0060', '\''); // grave accent
if (buffer.IndexOf('\u00B4') > -1) buffer = buffer.Replace('\u00B4', '\''); // acute accent if (buffer.IndexOf('\u2017') > -1)
{
buffer = buffer.Replace('\u2017', '_'); // double low line
}
if (buffer.IndexOf('\u2018') > -1)
{
buffer = buffer.Replace('\u2018', '\''); // left single quotation mark
}
if (buffer.IndexOf('\u2019') > -1)
{
buffer = buffer.Replace('\u2019', '\''); // right single quotation mark
}
if (buffer.IndexOf('\u201a') > -1)
{
buffer = buffer.Replace('\u201a', ','); // single low-9 quotation mark
}
if (buffer.IndexOf('\u201b') > -1)
{
buffer = buffer.Replace('\u201b', '\''); // single high-reversed-9 quotation mark
}
if (buffer.IndexOf('\u201c') > -1)
{
buffer = buffer.Replace('\u201c', '\"'); // left double quotation mark
}
if (buffer.IndexOf('\u201d') > -1)
{
buffer = buffer.Replace('\u201d', '\"'); // right double quotation mark
}
if (buffer.IndexOf('\u201e') > -1)
{
buffer = buffer.Replace('\u201e', '\"'); // double low-9 quotation mark
}
if (buffer.IndexOf('\u2026') > -1)
{
buffer = buffer.Replace("\u2026", "..."); // horizontal ellipsis
}
if (buffer.IndexOf('\u2032') > -1)
{
buffer = buffer.Replace('\u2032', '\''); // prime
}
if (buffer.IndexOf('\u2033') > -1)
{
buffer = buffer.Replace('\u2033', '\"'); // double prime
}
if (buffer.IndexOf('\u0060') > -1)
{
buffer = buffer.Replace('\u0060', '\''); // grave accent
}
if (buffer.IndexOf('\u00B4') > -1)
{
buffer = buffer.Replace('\u00B4', '\''); // acute accent
}
return buffer; return buffer;
} }
@ -6308,7 +6371,7 @@ where AncestorIdText not null and ItemValues.Value not null and ItemValues.Type
/// Gets the attachment. /// Gets the attachment.
/// </summary> /// </summary>
/// <param name="reader">The reader.</param> /// <param name="reader">The reader.</param>
/// <returns>MediaAttachment</returns> /// <returns>MediaAttachment.</returns>
private MediaAttachment GetMediaAttachment(IReadOnlyList<IResultSetValue> reader) private MediaAttachment GetMediaAttachment(IReadOnlyList<IResultSetValue> reader)
{ {
var item = new MediaAttachment var item = new MediaAttachment

@ -426,7 +426,7 @@ namespace Emby.Server.Implementations.HttpServer
/// </summary> /// </summary>
private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options) private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
{ {
bool noCache = (requestContext.Headers[HeaderNames.CacheControl].ToString()).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; bool noCache = requestContext.Headers[HeaderNames.CacheControl].ToString().IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1;
AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified); AddCachingHeaders(responseHeaders, options.CacheDuration, noCache, options.DateLastModified);
if (!noCache) if (!noCache)

@ -41,11 +41,11 @@ namespace Emby.Server.Implementations.HttpServer
res.Headers.Add(key, value); res.Headers.Add(key, value);
} }
// Try to prevent compatibility view // Try to prevent compatibility view
res.Headers["Access-Control-Allow-Headers"] = ("Accept, Accept-Language, Authorization, Cache-Control, " + res.Headers["Access-Control-Allow-Headers"] = "Accept, Accept-Language, Authorization, Cache-Control, " +
"Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, " + "Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, " +
"Content-Type, Cookie, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, " + "Content-Type, Cookie, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, " +
"Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, " + "Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, " +
"X-Emby-Authorization"); "X-Emby-Authorization";
if (dto is Exception exception) if (dto is Exception exception)
{ {

@ -136,7 +136,7 @@ namespace Emby.Server.Implementations.Library
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="LibraryManager" /> class. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
/// </summary> /// </summary>
/// <param name="appHost">The application host</param> /// <param name="appHost">The application host.</param>
/// <param name="logger">The logger.</param> /// <param name="logger">The logger.</param>
/// <param name="taskManager">The task manager.</param> /// <param name="taskManager">The task manager.</param>
/// <param name="userManager">The user manager.</param> /// <param name="userManager">The user manager.</param>
@ -1793,7 +1793,7 @@ namespace Emby.Server.Implementations.Library
/// Creates the items. /// Creates the items.
/// </summary> /// </summary>
/// <param name="items">The items.</param> /// <param name="items">The items.</param>
/// <param name="parent">The parent item</param> /// <param name="parent">The parent item.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken) public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
{ {

@ -19,7 +19,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books
// Only process items that are in a collection folder containing books // Only process items that are in a collection folder containing books
if (!string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase)) if (!string.Equals(collectionType, CollectionType.Books, StringComparison.OrdinalIgnoreCase))
{
return null; return null;
}
if (args.IsDirectory) if (args.IsDirectory)
{ {
@ -55,7 +57,9 @@ namespace Emby.Server.Implementations.Library.Resolvers.Books
// Don't return a Book if there is more (or less) than one document in the directory // Don't return a Book if there is more (or less) than one document in the directory
if (bookFiles.Count != 1) if (bookFiles.Count != 1)
{
return null; return null;
}
return new Book return new Book
{ {

@ -23,8 +23,8 @@ namespace Emby.Server.Implementations.Library.Resolvers.TV
/// </summary> /// </summary>
/// <param name="config">The config.</param> /// <param name="config">The config.</param>
/// <param name="libraryManager">The library manager.</param> /// <param name="libraryManager">The library manager.</param>
/// <param name="localization">The localization</param> /// <param name="localization">The localization.</param>
/// <param name="logger">The logger</param> /// <param name="logger">The logger.</param>
public SeasonResolver( public SeasonResolver(
IServerConfigurationManager config, IServerConfigurationManager config,
ILibraryManager libraryManager, ILibraryManager libraryManager,

@ -201,7 +201,14 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase); var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase);
var name = line.Substring(0, index - 1); var name = line.Substring(0, index - 1);
var currentChannel = line.Substring(index + 7); var currentChannel = line.Substring(index + 7);
if (currentChannel != "none") { status = LiveTvTunerStatus.LiveTv; } else { status = LiveTvTunerStatus.Available; } if (currentChannel != "none")
{
status = LiveTvTunerStatus.LiveTv;
}
else
{
status = LiveTvTunerStatus.Available;
}
tuners.Add(new LiveTvTunerInfo tuners.Add(new LiveTvTunerInfo
{ {
@ -691,7 +698,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
{ {
var model = ModelNumber ?? string.Empty; var model = ModelNumber ?? string.Empty;
if ((model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1)) if (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1)
{ {
return true; return true;
} }

@ -37,7 +37,10 @@ namespace Emby.Server.Implementations.Net
public UdpSocket(Socket socket, int localPort, IPAddress ip) public UdpSocket(Socket socket, int localPort, IPAddress ip)
{ {
if (socket == null) throw new ArgumentNullException(nameof(socket)); if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
_socket = socket; _socket = socket;
_localPort = localPort; _localPort = localPort;
@ -103,7 +106,10 @@ namespace Emby.Server.Implementations.Net
public UdpSocket(Socket socket, IPEndPoint endPoint) public UdpSocket(Socket socket, IPEndPoint endPoint)
{ {
if (socket == null) throw new ArgumentNullException(nameof(socket)); if (socket == null)
{
throw new ArgumentNullException(nameof(socket));
}
_socket = socket; _socket = socket;
_socket.Connect(endPoint); _socket.Connect(endPoint);

@ -539,13 +539,21 @@ namespace Emby.Server.Implementations.Playlists
private static string UnEscape(string content) private static string UnEscape(string content)
{ {
if (content == null) return content; if (content == null)
{
return content;
}
return content.Replace("&amp;", "&").Replace("&apos;", "'").Replace("&quot;", "\"").Replace("&gt;", ">").Replace("&lt;", "<"); return content.Replace("&amp;", "&").Replace("&apos;", "'").Replace("&quot;", "\"").Replace("&gt;", ">").Replace("&lt;", "<");
} }
private static string Escape(string content) private static string Escape(string content)
{ {
if (content == null) return null; if (content == null)
{
return null;
}
return content.Replace("&", "&amp;").Replace("'", "&apos;").Replace("\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;"); return content.Replace("&", "&amp;").Replace("'", "&apos;").Replace("\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;");
} }

@ -95,7 +95,7 @@ namespace Emby.Server.Implementations.ScheduledTasks
/// Queues the scheduled task. /// Queues the scheduled task.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="options">Task options</param> /// <param name="options">Task options.</param>
public void QueueScheduledTask<T>(TaskOptions options) public void QueueScheduledTask<T>(TaskOptions options)
where T : IScheduledTask where T : IScheduledTask
{ {

@ -98,7 +98,7 @@ namespace Emby.Server.Implementations.Security
statement.TryBind("@AppName", info.AppName); statement.TryBind("@AppName", info.AppName);
statement.TryBind("@AppVersion", info.AppVersion); statement.TryBind("@AppVersion", info.AppVersion);
statement.TryBind("@DeviceName", info.DeviceName); statement.TryBind("@DeviceName", info.DeviceName);
statement.TryBind("@UserId", (info.UserId.Equals(Guid.Empty) ? null : info.UserId.ToString("N", CultureInfo.InvariantCulture))); statement.TryBind("@UserId", info.UserId.Equals(Guid.Empty) ? null : info.UserId.ToString("N", CultureInfo.InvariantCulture));
statement.TryBind("@UserName", info.UserName); statement.TryBind("@UserName", info.UserName);
statement.TryBind("@IsActive", true); statement.TryBind("@IsActive", true);
statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue()); statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue());
@ -131,7 +131,7 @@ namespace Emby.Server.Implementations.Security
statement.TryBind("@AppName", info.AppName); statement.TryBind("@AppName", info.AppName);
statement.TryBind("@AppVersion", info.AppVersion); statement.TryBind("@AppVersion", info.AppVersion);
statement.TryBind("@DeviceName", info.DeviceName); statement.TryBind("@DeviceName", info.DeviceName);
statement.TryBind("@UserId", (info.UserId.Equals(Guid.Empty) ? null : info.UserId.ToString("N", CultureInfo.InvariantCulture))); statement.TryBind("@UserId", info.UserId.Equals(Guid.Empty) ? null : info.UserId.ToString("N", CultureInfo.InvariantCulture));
statement.TryBind("@UserName", info.UserName); statement.TryBind("@UserName", info.UserName);
statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue()); statement.TryBind("@DateCreated", info.DateCreated.ToDateTimeParamValue());
statement.TryBind("@DateLastActivity", info.DateLastActivity.ToDateTimeParamValue()); statement.TryBind("@DateLastActivity", info.DateLastActivity.ToDateTimeParamValue());

@ -40,7 +40,9 @@ namespace Emby.Server.Implementations.Services
if (httpResult != null) if (httpResult != null)
{ {
if (httpResult.RequestContext == null) if (httpResult.RequestContext == null)
{
httpResult.RequestContext = request; httpResult.RequestContext = request;
}
response.StatusCode = httpResult.Status; response.StatusCode = httpResult.Status;
} }

@ -144,7 +144,10 @@ namespace Emby.Server.Implementations.Services
var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts); var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts);
foreach (var potentialHashMatch in yieldedWildcardMatches) foreach (var potentialHashMatch in yieldedWildcardMatches)
{ {
if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue; if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches))
{
continue;
}
var bestScore = -1; var bestScore = -1;
RestPath bestMatch = null; RestPath bestMatch = null;

@ -42,11 +42,15 @@ namespace Emby.Server.Implementations.Services
} }
if (mi.GetParameters().Length != 1) if (mi.GetParameters().Length != 1)
{
continue; continue;
}
var actionName = mi.Name; var actionName = mi.Name;
if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase)) if (!AllVerbs.Contains(actionName, StringComparer.OrdinalIgnoreCase))
{
continue; continue;
}
list.Add(mi); list.Add(mi);
} }
@ -63,7 +67,10 @@ namespace Emby.Server.Implementations.Services
{ {
foreach (var actionCtx in actions) foreach (var actionCtx in actions)
{ {
if (execMap.ContainsKey(actionCtx.Id)) continue; if (execMap.ContainsKey(actionCtx.Id))
{
continue;
}
execMap[actionCtx.Id] = actionCtx; execMap[actionCtx.Id] = actionCtx;
} }

@ -124,7 +124,10 @@ namespace Emby.Server.Implementations.Services
var hasSeparators = new List<bool>(); var hasSeparators = new List<bool>();
foreach (var component in this.restPath.Split(PathSeperatorChar)) foreach (var component in this.restPath.Split(PathSeperatorChar))
{ {
if (string.IsNullOrEmpty(component)) continue; if (string.IsNullOrEmpty(component))
{
continue;
}
if (component.IndexOf(VariablePrefix, StringComparison.OrdinalIgnoreCase) != -1 if (component.IndexOf(VariablePrefix, StringComparison.OrdinalIgnoreCase) != -1
&& component.IndexOf(ComponentSeperator) != -1) && component.IndexOf(ComponentSeperator) != -1)
@ -302,9 +305,9 @@ namespace Emby.Server.Implementations.Services
} }
// Routes with least wildcard matches get the highest score // Routes with least wildcard matches get the highest score
var score = Math.Max((100 - wildcardMatchCount), 1) * 1000 var score = Math.Max(100 - wildcardMatchCount, 1) * 1000
// Routes with less variable (and more literal) matches // Routes with less variable (and more literal) matches
+ Math.Max((10 - VariableArgsCount), 1) * 100; + Math.Max(10 - VariableArgsCount, 1) * 100;
// Exact verb match is better than ANY // Exact verb match is better than ANY
if (Verbs.Length == 1 && string.Equals(httpMethod, Verbs[0], StringComparison.OrdinalIgnoreCase)) if (Verbs.Length == 1 && string.Equals(httpMethod, Verbs[0], StringComparison.OrdinalIgnoreCase))
@ -442,12 +445,14 @@ namespace Emby.Server.Implementations.Services
&& requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount; && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
if (!isValidWildCardPath) if (!isValidWildCardPath)
{
throw new ArgumentException( throw new ArgumentException(
string.Format( string.Format(
CultureInfo.InvariantCulture, CultureInfo.InvariantCulture,
"Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'", "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
pathInfo, pathInfo,
this.restPath)); this.restPath));
}
} }
var requestKeyValuesMap = new Dictionary<string, string>(); var requestKeyValuesMap = new Dictionary<string, string>();

@ -19,10 +19,14 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y) public int Compare(BaseItem x, BaseItem y)
{ {
if (x == null) if (x == null)
{
throw new ArgumentNullException(nameof(x)); throw new ArgumentNullException(nameof(x));
}
if (y == null) if (y == null)
{
throw new ArgumentNullException(nameof(y)); throw new ArgumentNullException(nameof(y));
}
return DateTime.Compare(x.DateCreated, y.DateCreated); return DateTime.Compare(x.DateCreated, y.DateCreated);
} }

@ -19,10 +19,14 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y) public int Compare(BaseItem x, BaseItem y)
{ {
if (x == null) if (x == null)
{
throw new ArgumentNullException(nameof(x)); throw new ArgumentNullException(nameof(x));
}
if (y == null) if (y == null)
{
throw new ArgumentNullException(nameof(y)); throw new ArgumentNullException(nameof(y));
}
return (x.RunTimeTicks ?? 0).CompareTo(y.RunTimeTicks ?? 0); return (x.RunTimeTicks ?? 0).CompareTo(y.RunTimeTicks ?? 0);
} }

@ -19,10 +19,14 @@ namespace Emby.Server.Implementations.Sorting
public int Compare(BaseItem x, BaseItem y) public int Compare(BaseItem x, BaseItem y)
{ {
if (x == null) if (x == null)
{
throw new ArgumentNullException(nameof(x)); throw new ArgumentNullException(nameof(x));
}
if (y == null) if (y == null)
{
throw new ArgumentNullException(nameof(y)); throw new ArgumentNullException(nameof(y));
}
return string.Compare(x.SortName, y.SortName, StringComparison.CurrentCultureIgnoreCase); return string.Compare(x.SortName, y.SortName, StringComparison.CurrentCultureIgnoreCase);
} }

@ -32,17 +32,28 @@ namespace Jellyfin.Data.Entities
/// <param name="_personrole1"></param> /// <param name="_personrole1"></param>
public Artwork(string path, Enums.ArtKind kind, Metadata _metadata0, PersonRole _personrole1) public Artwork(string path, Enums.ArtKind kind, Metadata _metadata0, PersonRole _personrole1)
{ {
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
this.Path = path; this.Path = path;
this.Kind = kind; this.Kind = kind;
if (_metadata0 == null) throw new ArgumentNullException(nameof(_metadata0)); if (_metadata0 == null)
{
throw new ArgumentNullException(nameof(_metadata0));
}
_metadata0.Artwork.Add(this); _metadata0.Artwork.Add(this);
if (_personrole1 == null) throw new ArgumentNullException(nameof(_personrole1)); if (_personrole1 == null)
_personrole1.Artwork = this; {
throw new ArgumentNullException(nameof(_personrole1));
}
_personrole1.Artwork = this;
Init(); Init();
} }
@ -87,7 +98,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -126,7 +137,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Path; string value = _Path;
GetPath(ref value); GetPath(ref value);
return (_Path = value); return _Path = value;
} }
set set
@ -163,7 +174,7 @@ namespace Jellyfin.Data.Entities
{ {
Enums.ArtKind value = _Kind; Enums.ArtKind value = _Kind;
GetKind(ref value); GetKind(ref value);
return (_Kind = value); return _Kind = value;
} }
set set

@ -29,18 +29,30 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_book0"></param> /// <param name="_book0"></param>
public BookMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Book _book0) public BookMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Book _book0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_book0 == null) throw new ArgumentNullException(nameof(_book0)); if (_book0 == null)
{
throw new ArgumentNullException(nameof(_book0));
}
_book0.BookMetadata.Add(this); _book0.BookMetadata.Add(this);
this.Publishers = new HashSet<Company>(); this.Publishers = new HashSet<Company>();
@ -51,8 +63,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_book0"></param> /// <param name="_book0"></param>
public static BookMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Book _book0) public static BookMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Book _book0)
{ {
@ -82,7 +94,7 @@ namespace Jellyfin.Data.Entities
{ {
long? value = _ISBN; long? value = _ISBN;
GetISBN(ref value); GetISBN(ref value);
return (_ISBN = value); return _ISBN = value;
} }
set set

@ -27,17 +27,25 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="timestart"></param> /// <param name="timestart"></param>
/// <param name="_release0"></param> /// <param name="_release0"></param>
public Chapter(string language, long timestart, Release _release0) public Chapter(string language, long timestart, Release _release0)
{ {
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
this.TimeStart = timestart; this.TimeStart = timestart;
if (_release0 == null) throw new ArgumentNullException(nameof(_release0)); if (_release0 == null)
{
throw new ArgumentNullException(nameof(_release0));
}
_release0.Chapters.Add(this); _release0.Chapters.Add(this);
@ -47,7 +55,7 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="timestart"></param> /// <param name="timestart"></param>
/// <param name="_release0"></param> /// <param name="_release0"></param>
public static Chapter Create(string language, long timestart, Release _release0) public static Chapter Create(string language, long timestart, Release _release0)
@ -84,7 +92,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -122,7 +130,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set
@ -163,7 +171,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Language; string value = _Language;
GetLanguage(ref value); GetLanguage(ref value);
return (_Language = value); return _Language = value;
} }
set set
@ -200,7 +208,7 @@ namespace Jellyfin.Data.Entities
{ {
long value = _TimeStart; long value = _TimeStart;
GetTimeStart(ref value); GetTimeStart(ref value);
return (_TimeStart = value); return _TimeStart = value;
} }
set set
@ -233,7 +241,7 @@ namespace Jellyfin.Data.Entities
{ {
long? value = _TimeEnd; long? value = _TimeEnd;
GetTimeEnd(ref value); GetTimeEnd(ref value);
return (_TimeEnd = value); return _TimeEnd = value;
} }
set set

@ -47,7 +47,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -85,7 +85,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set

@ -38,15 +38,26 @@ namespace Jellyfin.Data.Entities
// NOTE: This class has one-to-one associations with CollectionItem. // NOTE: This class has one-to-one associations with CollectionItem.
// One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other. // One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other.
if (_collection0 == null) throw new ArgumentNullException(nameof(_collection0)); if (_collection0 == null)
{
throw new ArgumentNullException(nameof(_collection0));
}
_collection0.CollectionItem.Add(this); _collection0.CollectionItem.Add(this);
if (_collectionitem1 == null) throw new ArgumentNullException(nameof(_collectionitem1)); if (_collectionitem1 == null)
{
throw new ArgumentNullException(nameof(_collectionitem1));
}
_collectionitem1.Next = this; _collectionitem1.Next = this;
if (_collectionitem2 == null) throw new ArgumentNullException(nameof(_collectionitem2)); if (_collectionitem2 == null)
_collectionitem2.Previous = this; {
throw new ArgumentNullException(nameof(_collectionitem2));
}
_collectionitem2.Previous = this;
Init(); Init();
} }
@ -91,7 +102,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set

@ -37,19 +37,39 @@ namespace Jellyfin.Data.Entities
/// <param name="_company4"></param> /// <param name="_company4"></param>
public Company(MovieMetadata _moviemetadata0, SeriesMetadata _seriesmetadata1, MusicAlbumMetadata _musicalbummetadata2, BookMetadata _bookmetadata3, Company _company4) public Company(MovieMetadata _moviemetadata0, SeriesMetadata _seriesmetadata1, MusicAlbumMetadata _musicalbummetadata2, BookMetadata _bookmetadata3, Company _company4)
{ {
if (_moviemetadata0 == null) throw new ArgumentNullException(nameof(_moviemetadata0)); if (_moviemetadata0 == null)
{
throw new ArgumentNullException(nameof(_moviemetadata0));
}
_moviemetadata0.Studios.Add(this); _moviemetadata0.Studios.Add(this);
if (_seriesmetadata1 == null) throw new ArgumentNullException(nameof(_seriesmetadata1)); if (_seriesmetadata1 == null)
{
throw new ArgumentNullException(nameof(_seriesmetadata1));
}
_seriesmetadata1.Networks.Add(this); _seriesmetadata1.Networks.Add(this);
if (_musicalbummetadata2 == null) throw new ArgumentNullException(nameof(_musicalbummetadata2)); if (_musicalbummetadata2 == null)
{
throw new ArgumentNullException(nameof(_musicalbummetadata2));
}
_musicalbummetadata2.Labels.Add(this); _musicalbummetadata2.Labels.Add(this);
if (_bookmetadata3 == null) throw new ArgumentNullException(nameof(_bookmetadata3)); if (_bookmetadata3 == null)
{
throw new ArgumentNullException(nameof(_bookmetadata3));
}
_bookmetadata3.Publishers.Add(this); _bookmetadata3.Publishers.Add(this);
if (_company4 == null) throw new ArgumentNullException(nameof(_company4)); if (_company4 == null)
{
throw new ArgumentNullException(nameof(_company4));
}
_company4.Parent = this; _company4.Parent = this;
this.CompanyMetadata = new HashSet<CompanyMetadata>(); this.CompanyMetadata = new HashSet<CompanyMetadata>();
@ -99,7 +119,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set

@ -26,20 +26,31 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_company0"></param> /// <param name="_company0"></param>
public CompanyMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Company _company0) public CompanyMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Company _company0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_company0 == null) throw new ArgumentNullException(nameof(_company0)); if (_company0 == null)
_company0.CompanyMetadata.Add(this); {
throw new ArgumentNullException(nameof(_company0));
}
_company0.CompanyMetadata.Add(this);
Init(); Init();
} }
@ -47,8 +58,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_company0"></param> /// <param name="_company0"></param>
public static CompanyMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Company _company0) public static CompanyMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Company _company0)
{ {
@ -83,7 +94,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Description; string value = _Description;
GetDescription(ref value); GetDescription(ref value);
return (_Description = value); return _Description = value;
} }
set set
@ -121,7 +132,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Headquarters; string value = _Headquarters;
GetHeadquarters(ref value); GetHeadquarters(ref value);
return (_Headquarters = value); return _Headquarters = value;
} }
set set
@ -159,7 +170,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Country; string value = _Country;
GetCountry(ref value); GetCountry(ref value);
return (_Country = value); return _Country = value;
} }
set set
@ -197,7 +208,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Homepage; string value = _Homepage;
GetHomepage(ref value); GetHomepage(ref value);
return (_Homepage = value); return _Homepage = value;
} }
set set

@ -25,20 +25,31 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_customitem0"></param> /// <param name="_customitem0"></param>
public CustomItemMetadata(string title, string language, DateTime dateadded, DateTime datemodified, CustomItem _customitem0) public CustomItemMetadata(string title, string language, DateTime dateadded, DateTime datemodified, CustomItem _customitem0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_customitem0 == null) throw new ArgumentNullException(nameof(_customitem0)); if (_customitem0 == null)
_customitem0.CustomItemMetadata.Add(this); {
throw new ArgumentNullException(nameof(_customitem0));
}
_customitem0.CustomItemMetadata.Add(this);
Init(); Init();
} }
@ -46,8 +57,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_customitem0"></param> /// <param name="_customitem0"></param>
public static CustomItemMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, CustomItem _customitem0) public static CustomItemMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, CustomItem _customitem0)
{ {

@ -42,7 +42,11 @@ namespace Jellyfin.Data.Entities
this.UrlId = urlid; this.UrlId = urlid;
if (_season0 == null) throw new ArgumentNullException(nameof(_season0)); if (_season0 == null)
{
throw new ArgumentNullException(nameof(_season0));
}
_season0.Episodes.Add(this); _season0.Episodes.Add(this);
this.Releases = new HashSet<Release>(); this.Releases = new HashSet<Release>();
@ -84,7 +88,7 @@ namespace Jellyfin.Data.Entities
{ {
int? value = _EpisodeNumber; int? value = _EpisodeNumber;
GetEpisodeNumber(ref value); GetEpisodeNumber(ref value);
return (_EpisodeNumber = value); return _EpisodeNumber = value;
} }
set set

@ -26,20 +26,31 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_episode0"></param> /// <param name="_episode0"></param>
public EpisodeMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Episode _episode0) public EpisodeMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Episode _episode0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_episode0 == null) throw new ArgumentNullException(nameof(_episode0)); if (_episode0 == null)
_episode0.EpisodeMetadata.Add(this); {
throw new ArgumentNullException(nameof(_episode0));
}
_episode0.EpisodeMetadata.Add(this);
Init(); Init();
} }
@ -47,8 +58,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_episode0"></param> /// <param name="_episode0"></param>
public static EpisodeMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Episode _episode0) public static EpisodeMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Episode _episode0)
{ {
@ -83,7 +94,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Outline; string value = _Outline;
GetOutline(ref value); GetOutline(ref value);
return (_Outline = value); return _Outline = value;
} }
set set
@ -121,7 +132,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Plot; string value = _Plot;
GetPlot(ref value); GetPlot(ref value);
return (_Plot = value); return _Plot = value;
} }
set set
@ -159,7 +170,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Tagline; string value = _Tagline;
GetTagline(ref value); GetTagline(ref value);
return (_Tagline = value); return _Tagline = value;
} }
set set

@ -31,12 +31,19 @@ namespace Jellyfin.Data.Entities
/// <param name="_metadata0"></param> /// <param name="_metadata0"></param>
public Genre(string name, Metadata _metadata0) public Genre(string name, Metadata _metadata0)
{ {
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
this.Name = name; this.Name = name;
if (_metadata0 == null) throw new ArgumentNullException(nameof(_metadata0)); if (_metadata0 == null)
_metadata0.Genres.Add(this); {
throw new ArgumentNullException(nameof(_metadata0));
}
_metadata0.Genres.Add(this);
Init(); Init();
} }
@ -80,7 +87,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -119,7 +126,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set

@ -99,7 +99,7 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="name">The name of this group</param> /// <param name="name">The name of this group.</param>
public static Group Create(string name) public static Group Create(string name)
{ {
return new Group(name); return new Group(name);

@ -30,9 +30,12 @@ namespace Jellyfin.Data.Entities
/// <param name="name"></param> /// <param name="name"></param>
public Library(string name) public Library(string name)
{ {
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrEmpty(name))
this.Name = name; {
throw new ArgumentNullException(nameof(name));
}
this.Name = name;
Init(); Init();
} }
@ -75,7 +78,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -114,7 +117,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set

@ -57,7 +57,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -95,7 +95,7 @@ namespace Jellyfin.Data.Entities
{ {
Guid value = _UrlId; Guid value = _UrlId;
GetUrlId(ref value); GetUrlId(ref value);
return (_UrlId = value); return _UrlId = value;
} }
set set
@ -132,7 +132,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTime value = _DateAdded; DateTime value = _DateAdded;
GetDateAdded(ref value); GetDateAdded(ref value);
return (_DateAdded = value); return _DateAdded = value;
} }
internal set internal set

@ -27,12 +27,15 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="path">Absolute Path</param> /// <param name="path">Absolute Path.</param>
public LibraryRoot(string path) public LibraryRoot(string path)
{ {
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (string.IsNullOrEmpty(path))
this.Path = path; {
throw new ArgumentNullException(nameof(path));
}
this.Path = path;
Init(); Init();
} }
@ -40,7 +43,7 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="path">Absolute Path</param> /// <param name="path">Absolute Path.</param>
public static LibraryRoot Create(string path) public static LibraryRoot Create(string path)
{ {
return new LibraryRoot(path); return new LibraryRoot(path);
@ -75,7 +78,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -115,7 +118,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Path; string value = _Path;
GetPath(ref value); GetPath(ref value);
return (_Path = value); return _Path = value;
} }
set set
@ -154,7 +157,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _NetworkPath; string value = _NetworkPath;
GetNetworkPath(ref value); GetNetworkPath(ref value);
return (_NetworkPath = value); return _NetworkPath = value;
} }
set set

@ -30,17 +30,25 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="path">Relative to the LibraryRoot</param> /// <param name="path">Relative to the LibraryRoot.</param>
/// <param name="kind"></param> /// <param name="kind"></param>
/// <param name="_release0"></param> /// <param name="_release0"></param>
public MediaFile(string path, Enums.MediaFileKind kind, Release _release0) public MediaFile(string path, Enums.MediaFileKind kind, Release _release0)
{ {
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
this.Path = path; this.Path = path;
this.Kind = kind; this.Kind = kind;
if (_release0 == null) throw new ArgumentNullException(nameof(_release0)); if (_release0 == null)
{
throw new ArgumentNullException(nameof(_release0));
}
_release0.MediaFiles.Add(this); _release0.MediaFiles.Add(this);
this.MediaFileStreams = new HashSet<MediaFileStream>(); this.MediaFileStreams = new HashSet<MediaFileStream>();
@ -51,7 +59,7 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="path">Relative to the LibraryRoot</param> /// <param name="path">Relative to the LibraryRoot.</param>
/// <param name="kind"></param> /// <param name="kind"></param>
/// <param name="_release0"></param> /// <param name="_release0"></param>
public static MediaFile Create(string path, Enums.MediaFileKind kind, Release _release0) public static MediaFile Create(string path, Enums.MediaFileKind kind, Release _release0)
@ -88,7 +96,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -128,7 +136,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Path; string value = _Path;
GetPath(ref value); GetPath(ref value);
return (_Path = value); return _Path = value;
} }
set set
@ -165,7 +173,7 @@ namespace Jellyfin.Data.Entities
{ {
Enums.MediaFileKind value = _Kind; Enums.MediaFileKind value = _Kind;
GetKind(ref value); GetKind(ref value);
return (_Kind = value); return _Kind = value;
} }
set set

@ -33,9 +33,12 @@ namespace Jellyfin.Data.Entities
{ {
this.StreamNumber = streamnumber; this.StreamNumber = streamnumber;
if (_mediafile0 == null) throw new ArgumentNullException(nameof(_mediafile0)); if (_mediafile0 == null)
_mediafile0.MediaFileStreams.Add(this); {
throw new ArgumentNullException(nameof(_mediafile0));
}
_mediafile0.MediaFileStreams.Add(this);
Init(); Init();
} }
@ -79,7 +82,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -116,7 +119,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _StreamNumber; int value = _StreamNumber;
GetStreamNumber(ref value); GetStreamNumber(ref value);
return (_StreamNumber = value); return _StreamNumber = value;
} }
set set

@ -26,14 +26,22 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
protected Metadata(string title, string language, DateTime dateadded, DateTime datemodified) protected Metadata(string title, string language, DateTime dateadded, DateTime datemodified)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
this.PersonRoles = new HashSet<PersonRole>(); this.PersonRoles = new HashSet<PersonRole>();
@ -74,7 +82,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -114,7 +122,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Title; string value = _Title;
GetTitle(ref value); GetTitle(ref value);
return (_Title = value); return _Title = value;
} }
set set
@ -152,7 +160,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _OriginalTitle; string value = _OriginalTitle;
GetOriginalTitle(ref value); GetOriginalTitle(ref value);
return (_OriginalTitle = value); return _OriginalTitle = value;
} }
set set
@ -190,7 +198,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _SortTitle; string value = _SortTitle;
GetSortTitle(ref value); GetSortTitle(ref value);
return (_SortTitle = value); return _SortTitle = value;
} }
set set
@ -231,7 +239,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Language; string value = _Language;
GetLanguage(ref value); GetLanguage(ref value);
return (_Language = value); return _Language = value;
} }
set set
@ -264,7 +272,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTimeOffset? value = _ReleaseDate; DateTimeOffset? value = _ReleaseDate;
GetReleaseDate(ref value); GetReleaseDate(ref value);
return (_ReleaseDate = value); return _ReleaseDate = value;
} }
set set
@ -301,7 +309,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTime value = _DateAdded; DateTime value = _DateAdded;
GetDateAdded(ref value); GetDateAdded(ref value);
return (_DateAdded = value); return _DateAdded = value;
} }
internal set internal set
@ -338,7 +346,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTime value = _DateModified; DateTime value = _DateModified;
GetDateModified(ref value); GetDateModified(ref value);
return (_DateModified = value); return _DateModified = value;
} }
internal set internal set

@ -30,9 +30,12 @@ namespace Jellyfin.Data.Entities
/// <param name="name"></param> /// <param name="name"></param>
public MetadataProvider(string name) public MetadataProvider(string name)
{ {
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrEmpty(name))
this.Name = name; {
throw new ArgumentNullException(nameof(name));
}
this.Name = name;
Init(); Init();
} }
@ -75,7 +78,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -114,7 +117,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set

@ -40,21 +40,40 @@ namespace Jellyfin.Data.Entities
// NOTE: This class has one-to-one associations with MetadataProviderId. // NOTE: This class has one-to-one associations with MetadataProviderId.
// One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other. // One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other.
if (string.IsNullOrEmpty(providerid)) throw new ArgumentNullException(nameof(providerid)); if (string.IsNullOrEmpty(providerid))
{
throw new ArgumentNullException(nameof(providerid));
}
this.ProviderId = providerid; this.ProviderId = providerid;
if (_metadata0 == null) throw new ArgumentNullException(nameof(_metadata0)); if (_metadata0 == null)
{
throw new ArgumentNullException(nameof(_metadata0));
}
_metadata0.Sources.Add(this); _metadata0.Sources.Add(this);
if (_person1 == null) throw new ArgumentNullException(nameof(_person1)); if (_person1 == null)
{
throw new ArgumentNullException(nameof(_person1));
}
_person1.Sources.Add(this); _person1.Sources.Add(this);
if (_personrole2 == null) throw new ArgumentNullException(nameof(_personrole2)); if (_personrole2 == null)
{
throw new ArgumentNullException(nameof(_personrole2));
}
_personrole2.Sources.Add(this); _personrole2.Sources.Add(this);
if (_ratingsource3 == null) throw new ArgumentNullException(nameof(_ratingsource3)); if (_ratingsource3 == null)
_ratingsource3.Source = this; {
throw new ArgumentNullException(nameof(_ratingsource3));
}
_ratingsource3.Source = this;
Init(); Init();
} }
@ -101,7 +120,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -140,7 +159,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _ProviderId; string value = _ProviderId;
GetProviderId(ref value); GetProviderId(ref value);
return (_ProviderId = value); return _ProviderId = value;
} }
set set

@ -30,18 +30,30 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_movie0"></param> /// <param name="_movie0"></param>
public MovieMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Movie _movie0) public MovieMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Movie _movie0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_movie0 == null) throw new ArgumentNullException(nameof(_movie0)); if (_movie0 == null)
{
throw new ArgumentNullException(nameof(_movie0));
}
_movie0.MovieMetadata.Add(this); _movie0.MovieMetadata.Add(this);
this.Studios = new HashSet<Company>(); this.Studios = new HashSet<Company>();
@ -52,8 +64,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_movie0"></param> /// <param name="_movie0"></param>
public static MovieMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Movie _movie0) public static MovieMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Movie _movie0)
{ {
@ -88,7 +100,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Outline; string value = _Outline;
GetOutline(ref value); GetOutline(ref value);
return (_Outline = value); return _Outline = value;
} }
set set
@ -126,7 +138,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Plot; string value = _Plot;
GetPlot(ref value); GetPlot(ref value);
return (_Plot = value); return _Plot = value;
} }
set set
@ -164,7 +176,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Tagline; string value = _Tagline;
GetTagline(ref value); GetTagline(ref value);
return (_Tagline = value); return _Tagline = value;
} }
set set
@ -202,7 +214,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Country; string value = _Country;
GetCountry(ref value); GetCountry(ref value);
return (_Country = value); return _Country = value;
} }
set set

@ -30,18 +30,30 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_musicalbum0"></param> /// <param name="_musicalbum0"></param>
public MusicAlbumMetadata(string title, string language, DateTime dateadded, DateTime datemodified, MusicAlbum _musicalbum0) public MusicAlbumMetadata(string title, string language, DateTime dateadded, DateTime datemodified, MusicAlbum _musicalbum0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_musicalbum0 == null) throw new ArgumentNullException(nameof(_musicalbum0)); if (_musicalbum0 == null)
{
throw new ArgumentNullException(nameof(_musicalbum0));
}
_musicalbum0.MusicAlbumMetadata.Add(this); _musicalbum0.MusicAlbumMetadata.Add(this);
this.Labels = new HashSet<Company>(); this.Labels = new HashSet<Company>();
@ -52,8 +64,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_musicalbum0"></param> /// <param name="_musicalbum0"></param>
public static MusicAlbumMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, MusicAlbum _musicalbum0) public static MusicAlbumMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, MusicAlbum _musicalbum0)
{ {
@ -88,7 +100,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Barcode; string value = _Barcode;
GetBarcode(ref value); GetBarcode(ref value);
return (_Barcode = value); return _Barcode = value;
} }
set set
@ -126,7 +138,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _LabelNumber; string value = _LabelNumber;
GetLabelNumber(ref value); GetLabelNumber(ref value);
return (_LabelNumber = value); return _LabelNumber = value;
} }
set set
@ -164,7 +176,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Country; string value = _Country;
GetCountry(ref value); GetCountry(ref value);
return (_Country = value); return _Country = value;
} }
set set

@ -36,7 +36,11 @@ namespace Jellyfin.Data.Entities
{ {
this.UrlId = urlid; this.UrlId = urlid;
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
this.Name = name; this.Name = name;
this.Sources = new HashSet<MetadataProviderId>(); this.Sources = new HashSet<MetadataProviderId>();
@ -83,7 +87,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -120,7 +124,7 @@ namespace Jellyfin.Data.Entities
{ {
Guid value = _UrlId; Guid value = _UrlId;
GetUrlId(ref value); GetUrlId(ref value);
return (_UrlId = value); return _UrlId = value;
} }
set set
@ -159,7 +163,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set
@ -197,7 +201,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _SourceId; string value = _SourceId;
GetSourceId(ref value); GetSourceId(ref value);
return (_SourceId = value); return _SourceId = value;
} }
set set
@ -234,7 +238,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTime value = _DateAdded; DateTime value = _DateAdded;
GetDateAdded(ref value); GetDateAdded(ref value);
return (_DateAdded = value); return _DateAdded = value;
} }
internal set internal set
@ -271,7 +275,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTime value = _DateModified; DateTime value = _DateModified;
GetDateModified(ref value); GetDateModified(ref value);
return (_DateModified = value); return _DateModified = value;
} }
internal set internal set

@ -42,7 +42,11 @@ namespace Jellyfin.Data.Entities
this.Type = type; this.Type = type;
if (_metadata0 == null) throw new ArgumentNullException(nameof(_metadata0)); if (_metadata0 == null)
{
throw new ArgumentNullException(nameof(_metadata0));
}
_metadata0.PersonRoles.Add(this); _metadata0.PersonRoles.Add(this);
this.Sources = new HashSet<MetadataProviderId>(); this.Sources = new HashSet<MetadataProviderId>();
@ -89,7 +93,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -127,7 +131,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Role; string value = _Role;
GetRole(ref value); GetRole(ref value);
return (_Role = value); return _Role = value;
} }
set set
@ -164,7 +168,7 @@ namespace Jellyfin.Data.Entities
{ {
Enums.PersonRoleType value = _Type; Enums.PersonRoleType value = _Type;
GetType(ref value); GetType(ref value);
return (_Type = value); return _Type = value;
} }
set set

@ -26,20 +26,31 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_photo0"></param> /// <param name="_photo0"></param>
public PhotoMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Photo _photo0) public PhotoMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Photo _photo0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_photo0 == null) throw new ArgumentNullException(nameof(_photo0)); if (_photo0 == null)
_photo0.PhotoMetadata.Add(this); {
throw new ArgumentNullException(nameof(_photo0));
}
_photo0.PhotoMetadata.Add(this);
Init(); Init();
} }
@ -47,8 +58,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_photo0"></param> /// <param name="_photo0"></param>
public static PhotoMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Photo _photo0) public static PhotoMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Photo _photo0)
{ {

@ -34,15 +34,26 @@ namespace Jellyfin.Data.Entities
/// <param name="_group1"></param> /// <param name="_group1"></param>
public ProviderMapping(string providername, string providersecrets, string providerdata, User _user0, Group _group1) public ProviderMapping(string providername, string providersecrets, string providerdata, User _user0, Group _group1)
{ {
if (string.IsNullOrEmpty(providername)) throw new ArgumentNullException(nameof(providername)); if (string.IsNullOrEmpty(providername))
{
throw new ArgumentNullException(nameof(providername));
}
this.ProviderName = providername; this.ProviderName = providername;
if (string.IsNullOrEmpty(providersecrets)) throw new ArgumentNullException(nameof(providersecrets)); if (string.IsNullOrEmpty(providersecrets))
{
throw new ArgumentNullException(nameof(providersecrets));
}
this.ProviderSecrets = providersecrets; this.ProviderSecrets = providersecrets;
if (string.IsNullOrEmpty(providerdata)) throw new ArgumentNullException(nameof(providerdata)); if (string.IsNullOrEmpty(providerdata))
this.ProviderData = providerdata; {
throw new ArgumentNullException(nameof(providerdata));
}
this.ProviderData = providerdata;
Init(); Init();
} }

@ -33,9 +33,12 @@ namespace Jellyfin.Data.Entities
{ {
this.Value = value; this.Value = value;
if (_metadata0 == null) throw new ArgumentNullException(nameof(_metadata0)); if (_metadata0 == null)
_metadata0.Ratings.Add(this); {
throw new ArgumentNullException(nameof(_metadata0));
}
_metadata0.Ratings.Add(this);
Init(); Init();
} }
@ -79,7 +82,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -116,7 +119,7 @@ namespace Jellyfin.Data.Entities
{ {
double value = _Value; double value = _Value;
GetValue(ref value); GetValue(ref value);
return (_Value = value); return _Value = value;
} }
set set
@ -149,7 +152,7 @@ namespace Jellyfin.Data.Entities
{ {
int? value = _Votes; int? value = _Votes;
GetVotes(ref value); GetVotes(ref value);
return (_Votes = value); return _Votes = value;
} }
set set

@ -39,9 +39,12 @@ namespace Jellyfin.Data.Entities
this.MinimumValue = minimumvalue; this.MinimumValue = minimumvalue;
if (_rating0 == null) throw new ArgumentNullException(nameof(_rating0)); if (_rating0 == null)
_rating0.RatingType = this; {
throw new ArgumentNullException(nameof(_rating0));
}
_rating0.RatingType = this;
Init(); Init();
} }
@ -86,7 +89,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -124,7 +127,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set
@ -161,7 +164,7 @@ namespace Jellyfin.Data.Entities
{ {
double value = _MaximumValue; double value = _MaximumValue;
GetMaximumValue(ref value); GetMaximumValue(ref value);
return (_MaximumValue = value); return _MaximumValue = value;
} }
set set
@ -198,7 +201,7 @@ namespace Jellyfin.Data.Entities
{ {
double value = _MinimumValue; double value = _MinimumValue;
GetMinimumValue(ref value); GetMinimumValue(ref value);
return (_MinimumValue = value); return _MinimumValue = value;
} }
set set

@ -40,25 +40,53 @@ namespace Jellyfin.Data.Entities
/// <param name="_photo5"></param> /// <param name="_photo5"></param>
public Release(string name, Movie _movie0, Episode _episode1, Track _track2, CustomItem _customitem3, Book _book4, Photo _photo5) public Release(string name, Movie _movie0, Episode _episode1, Track _track2, CustomItem _customitem3, Book _book4, Photo _photo5)
{ {
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
this.Name = name; this.Name = name;
if (_movie0 == null) throw new ArgumentNullException(nameof(_movie0)); if (_movie0 == null)
{
throw new ArgumentNullException(nameof(_movie0));
}
_movie0.Releases.Add(this); _movie0.Releases.Add(this);
if (_episode1 == null) throw new ArgumentNullException(nameof(_episode1)); if (_episode1 == null)
{
throw new ArgumentNullException(nameof(_episode1));
}
_episode1.Releases.Add(this); _episode1.Releases.Add(this);
if (_track2 == null) throw new ArgumentNullException(nameof(_track2)); if (_track2 == null)
{
throw new ArgumentNullException(nameof(_track2));
}
_track2.Releases.Add(this); _track2.Releases.Add(this);
if (_customitem3 == null) throw new ArgumentNullException(nameof(_customitem3)); if (_customitem3 == null)
{
throw new ArgumentNullException(nameof(_customitem3));
}
_customitem3.Releases.Add(this); _customitem3.Releases.Add(this);
if (_book4 == null) throw new ArgumentNullException(nameof(_book4)); if (_book4 == null)
{
throw new ArgumentNullException(nameof(_book4));
}
_book4.Releases.Add(this); _book4.Releases.Add(this);
if (_photo5 == null) throw new ArgumentNullException(nameof(_photo5)); if (_photo5 == null)
{
throw new ArgumentNullException(nameof(_photo5));
}
_photo5.Releases.Add(this); _photo5.Releases.Add(this);
this.MediaFiles = new HashSet<MediaFile>(); this.MediaFiles = new HashSet<MediaFile>();
@ -111,7 +139,7 @@ namespace Jellyfin.Data.Entities
{ {
int value = _Id; int value = _Id;
GetId(ref value); GetId(ref value);
return (_Id = value); return _Id = value;
} }
protected set protected set
@ -150,7 +178,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Name; string value = _Name;
GetName(ref value); GetName(ref value);
return (_Name = value); return _Name = value;
} }
set set

@ -42,7 +42,11 @@ namespace Jellyfin.Data.Entities
this.UrlId = urlid; this.UrlId = urlid;
if (_series0 == null) throw new ArgumentNullException(nameof(_series0)); if (_series0 == null)
{
throw new ArgumentNullException(nameof(_series0));
}
_series0.Seasons.Add(this); _series0.Seasons.Add(this);
this.SeasonMetadata = new HashSet<SeasonMetadata>(); this.SeasonMetadata = new HashSet<SeasonMetadata>();
@ -84,7 +88,7 @@ namespace Jellyfin.Data.Entities
{ {
int? value = _SeasonNumber; int? value = _SeasonNumber;
GetSeasonNumber(ref value); GetSeasonNumber(ref value);
return (_SeasonNumber = value); return _SeasonNumber = value;
} }
set set

@ -27,20 +27,31 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_season0"></param> /// <param name="_season0"></param>
public SeasonMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Season _season0) public SeasonMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Season _season0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_season0 == null) throw new ArgumentNullException(nameof(_season0)); if (_season0 == null)
_season0.SeasonMetadata.Add(this); {
throw new ArgumentNullException(nameof(_season0));
}
_season0.SeasonMetadata.Add(this);
Init(); Init();
} }
@ -48,8 +59,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_season0"></param> /// <param name="_season0"></param>
public static SeasonMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Season _season0) public static SeasonMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Season _season0)
{ {
@ -84,7 +95,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Outline; string value = _Outline;
GetOutline(ref value); GetOutline(ref value);
return (_Outline = value); return _Outline = value;
} }
set set

@ -65,7 +65,7 @@ namespace Jellyfin.Data.Entities
{ {
DayOfWeek? value = _AirsDayOfWeek; DayOfWeek? value = _AirsDayOfWeek;
GetAirsDayOfWeek(ref value); GetAirsDayOfWeek(ref value);
return (_AirsDayOfWeek = value); return _AirsDayOfWeek = value;
} }
set set
@ -101,7 +101,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTimeOffset? value = _AirsTime; DateTimeOffset? value = _AirsTime;
GetAirsTime(ref value); GetAirsTime(ref value);
return (_AirsTime = value); return _AirsTime = value;
} }
set set
@ -134,7 +134,7 @@ namespace Jellyfin.Data.Entities
{ {
DateTimeOffset? value = _FirstAired; DateTimeOffset? value = _FirstAired;
GetFirstAired(ref value); GetFirstAired(ref value);
return (_FirstAired = value); return _FirstAired = value;
} }
set set

@ -30,18 +30,30 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_series0"></param> /// <param name="_series0"></param>
public SeriesMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Series _series0) public SeriesMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Series _series0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_series0 == null) throw new ArgumentNullException(nameof(_series0)); if (_series0 == null)
{
throw new ArgumentNullException(nameof(_series0));
}
_series0.SeriesMetadata.Add(this); _series0.SeriesMetadata.Add(this);
this.Networks = new HashSet<Company>(); this.Networks = new HashSet<Company>();
@ -52,8 +64,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_series0"></param> /// <param name="_series0"></param>
public static SeriesMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Series _series0) public static SeriesMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Series _series0)
{ {
@ -88,7 +100,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Outline; string value = _Outline;
GetOutline(ref value); GetOutline(ref value);
return (_Outline = value); return _Outline = value;
} }
set set
@ -126,7 +138,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Plot; string value = _Plot;
GetPlot(ref value); GetPlot(ref value);
return (_Plot = value); return _Plot = value;
} }
set set
@ -164,7 +176,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Tagline; string value = _Tagline;
GetTagline(ref value); GetTagline(ref value);
return (_Tagline = value); return _Tagline = value;
} }
set set
@ -202,7 +214,7 @@ namespace Jellyfin.Data.Entities
{ {
string value = _Country; string value = _Country;
GetCountry(ref value); GetCountry(ref value);
return (_Country = value); return _Country = value;
} }
set set

@ -42,7 +42,11 @@ namespace Jellyfin.Data.Entities
this.UrlId = urlid; this.UrlId = urlid;
if (_musicalbum0 == null) throw new ArgumentNullException(nameof(_musicalbum0)); if (_musicalbum0 == null)
{
throw new ArgumentNullException(nameof(_musicalbum0));
}
_musicalbum0.Tracks.Add(this); _musicalbum0.Tracks.Add(this);
this.Releases = new HashSet<Release>(); this.Releases = new HashSet<Release>();
@ -84,7 +88,7 @@ namespace Jellyfin.Data.Entities
{ {
int? value = _TrackNumber; int? value = _TrackNumber;
GetTrackNumber(ref value); GetTrackNumber(ref value);
return (_TrackNumber = value); return _TrackNumber = value;
} }
set set

@ -26,20 +26,31 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Public constructor with required data. /// Public constructor with required data.
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_track0"></param> /// <param name="_track0"></param>
public TrackMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Track _track0) public TrackMetadata(string title, string language, DateTime dateadded, DateTime datemodified, Track _track0)
{ {
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
this.Title = title; this.Title = title;
if (string.IsNullOrEmpty(language)) throw new ArgumentNullException(nameof(language)); if (string.IsNullOrEmpty(language))
{
throw new ArgumentNullException(nameof(language));
}
this.Language = language; this.Language = language;
if (_track0 == null) throw new ArgumentNullException(nameof(_track0)); if (_track0 == null)
_track0.TrackMetadata.Add(this); {
throw new ArgumentNullException(nameof(_track0));
}
_track0.TrackMetadata.Add(this);
Init(); Init();
} }
@ -47,8 +58,8 @@ namespace Jellyfin.Data.Entities
/// <summary> /// <summary>
/// Static create function (for use in LINQ queries, etc.) /// Static create function (for use in LINQ queries, etc.)
/// </summary> /// </summary>
/// <param name="title">The title or name of the object</param> /// <param name="title">The title or name of the object.</param>
/// <param name="language">ISO-639-3 3-character language codes</param> /// <param name="language">ISO-639-3 3-character language codes.</param>
/// <param name="_track0"></param> /// <param name="_track0"></param>
public static TrackMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Track _track0) public static TrackMetadata Create(string title, string language, DateTime dateadded, DateTime datemodified, Track _track0)
{ {

@ -30,7 +30,7 @@ namespace MediaBrowser.Controller.Drawing
/// Gets the dimensions of the image. /// Gets the dimensions of the image.
/// </summary> /// </summary>
/// <param name="path">Path to the image file.</param> /// <param name="path">Path to the image file.</param>
/// <returns>ImageDimensions</returns> /// <returns>ImageDimensions.</returns>
ImageDimensions GetImageDimensions(string path); ImageDimensions GetImageDimensions(string path);
/// <summary> /// <summary>
@ -38,14 +38,14 @@ namespace MediaBrowser.Controller.Drawing
/// </summary> /// </summary>
/// <param name="item">The base item.</param> /// <param name="item">The base item.</param>
/// <param name="info">The information.</param> /// <param name="info">The information.</param>
/// <returns>ImageDimensions</returns> /// <returns>ImageDimensions.</returns>
ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info); ImageDimensions GetImageDimensions(BaseItem item, ItemImageInfo info);
/// <summary> /// <summary>
/// Gets the blurhash of the image. /// Gets the blurhash of the image.
/// </summary> /// </summary>
/// <param name="path">Path to the image file.</param> /// <param name="path">Path to the image file.</param>
/// <returns>BlurHash</returns> /// <returns>BlurHash.</returns>
string GetImageBlurHash(string path); string GetImageBlurHash(string path);
/// <summary> /// <summary>

@ -690,7 +690,10 @@ namespace MediaBrowser.Controller.Entities
/// <returns>System.String.</returns> /// <returns>System.String.</returns>
protected virtual string CreateSortName() protected virtual string CreateSortName()
{ {
if (Name == null) return null; // some items may not have name filled in properly if (Name == null)
{
return null; // some items may not have name filled in properly
}
if (!EnableAlphaNumericSorting) if (!EnableAlphaNumericSorting)
{ {
@ -1371,7 +1374,7 @@ namespace MediaBrowser.Controller.Entities
/// </summary> /// </summary>
/// <param name="options">The options.</param> /// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>true if a provider reports we changed</returns> /// <returns>true if a provider reports we changed.</returns>
public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken) public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
{ {
TriggerOnRefreshStart(); TriggerOnRefreshStart();
@ -2948,9 +2951,13 @@ namespace MediaBrowser.Controller.Entities
public IEnumerable<BaseItem> GetTrailers() public IEnumerable<BaseItem> GetTrailers()
{ {
if (this is IHasTrailers) if (this is IHasTrailers)
{
return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName); return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
}
else else
{
return Array.Empty<BaseItem>(); return Array.Empty<BaseItem>();
}
} }
public virtual bool IsHD => Height >= 720; public virtual bool IsHD => Height >= 720;

@ -225,7 +225,7 @@ namespace MediaBrowser.Controller.Entities
return null; return null;
} }
return (totalProgresses / foldersWithProgress); return totalProgresses / foldersWithProgress;
} }
protected override bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren) protected override bool RefreshLinkedChildren(IEnumerable<FileSystemMetadata> fileSystemChildren)

@ -480,7 +480,7 @@ namespace MediaBrowser.Controller.Entities
innerProgress.RegisterAction(p => innerProgress.RegisterAction(p =>
{ {
double innerPercent = currentInnerPercent; double innerPercent = currentInnerPercent;
innerPercent += p / (count); innerPercent += p / count;
progress.Report(innerPercent); progress.Report(innerPercent);
}); });
@ -556,7 +556,7 @@ namespace MediaBrowser.Controller.Entities
innerProgress.RegisterAction(p => innerProgress.RegisterAction(p =>
{ {
double innerPercent = currentInnerPercent; double innerPercent = currentInnerPercent;
innerPercent += p / (count); innerPercent += p / count;
progress.Report(innerPercent); progress.Report(innerPercent);
}); });

@ -42,7 +42,7 @@ namespace MediaBrowser.Controller.Library
public LibraryOptions GetLibraryOptions() public LibraryOptions GetLibraryOptions()
{ {
return LibraryOptions ?? (LibraryOptions = (Parent == null ? new LibraryOptions() : BaseItem.LibraryManager.GetLibraryOptions(Parent))); return LibraryOptions ?? (LibraryOptions = Parent == null ? new LibraryOptions() : BaseItem.LibraryManager.GetLibraryOptions(Parent));
} }
/// <summary> /// <summary>
@ -224,8 +224,6 @@ namespace MediaBrowser.Controller.Library
public string CollectionType { get; set; } public string CollectionType { get; set; }
#region Equality Overrides
/// <summary> /// <summary>
/// Determines whether the specified <see cref="object" /> is equal to this instance. /// Determines whether the specified <see cref="object" /> is equal to this instance.
/// </summary> /// </summary>
@ -254,14 +252,15 @@ namespace MediaBrowser.Controller.Library
{ {
if (args != null) if (args != null)
{ {
if (args.Path == null && Path == null) return true; if (args.Path == null && Path == null)
{
return true;
}
return args.Path != null && BaseItem.FileSystem.AreEqual(args.Path, Path); return args.Path != null && BaseItem.FileSystem.AreEqual(args.Path, Path);
} }
return false; return false;
} }
#endregion
} }
} }

@ -37,7 +37,6 @@ namespace MediaBrowser.Controller.Library
_stopwatch = new Stopwatch(); _stopwatch = new Stopwatch();
_stopwatch.Start(); _stopwatch.Start();
} }
#region IDisposable Members
/// <summary> /// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
@ -71,7 +70,5 @@ namespace MediaBrowser.Controller.Library
_logger.LogInformation(message); _logger.LogInformation(message);
} }
} }
#endregion
} }
} }

@ -2603,6 +2603,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{ {
return "-c:v vp8_qsv"; return "-c:v vp8_qsv";
} }
break; break;
case "vp9": case "vp9":
if (_mediaEncoder.SupportsDecoder("vp9_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("vp9_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
@ -2610,6 +2611,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return (isColorDepth10 && return (isColorDepth10 &&
!encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_qsv"; !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_qsv";
} }
break; break;
} }
} }
@ -2667,6 +2669,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{ {
return "-c:v vp8_cuvid"; return "-c:v vp8_cuvid";
} }
break; break;
case "vp9": case "vp9":
if (_mediaEncoder.SupportsDecoder("vp9_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("vp9_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
@ -2674,6 +2677,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return (isColorDepth10 && return (isColorDepth10 &&
!encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_cuvid"; !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_cuvid";
} }
break; break;
} }
} }
@ -2818,6 +2822,7 @@ namespace MediaBrowser.Controller.MediaEncoding
{ {
return "-c:v h264_opencl"; return "-c:v h264_opencl";
} }
break; break;
case "hevc": case "hevc":
case "h265": case "h265":
@ -2826,30 +2831,35 @@ namespace MediaBrowser.Controller.MediaEncoding
return (isColorDepth10 && return (isColorDepth10 &&
!encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_opencl"; !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_opencl";
} }
break; break;
case "mpeg2video": case "mpeg2video":
if (_mediaEncoder.SupportsDecoder("mpeg2_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("mpeg2_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
{ {
return "-c:v mpeg2_opencl"; return "-c:v mpeg2_opencl";
} }
break; break;
case "mpeg4": case "mpeg4":
if (_mediaEncoder.SupportsDecoder("mpeg4_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("mpeg4_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
{ {
return "-c:v mpeg4_opencl"; return "-c:v mpeg4_opencl";
} }
break; break;
case "vc1": case "vc1":
if (_mediaEncoder.SupportsDecoder("vc1_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("vc1_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
{ {
return "-c:v vc1_opencl"; return "-c:v vc1_opencl";
} }
break; break;
case "vp8": case "vp8":
if (_mediaEncoder.SupportsDecoder("vp8_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("vp8_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
{ {
return "-c:v vp8_opencl"; return "-c:v vp8_opencl";
} }
break; break;
case "vp9": case "vp9":
if (_mediaEncoder.SupportsDecoder("vp9_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase)) if (_mediaEncoder.SupportsDecoder("vp9_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
@ -2857,6 +2867,7 @@ namespace MediaBrowser.Controller.MediaEncoding
return (isColorDepth10 && return (isColorDepth10 &&
!encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_opencl"; !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_opencl";
} }
break; break;
} }
} }

@ -31,9 +31,9 @@ namespace MediaBrowser.Controller.Net
/// <summary> /// <summary>
/// The request filter is executed before the service. /// The request filter is executed before the service.
/// </summary> /// </summary>
/// <param name="request">The http request wrapper</param> /// <param name="request">The http request wrapper.</param>
/// <param name="response">The http response wrapper</param> /// <param name="response">The http response wrapper.</param>
/// <param name="requestDto">The request DTO</param> /// <param name="requestDto">The request DTO.</param>
public void RequestFilter(IRequest request, HttpResponse response, object requestDto) public void RequestFilter(IRequest request, HttpResponse response, object requestDto)
{ {
AuthService.Authenticate(request, this); AuthService.Authenticate(request, this);

@ -27,7 +27,7 @@ namespace MediaBrowser.Controller.Net
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SecurityException"/> class. /// Initializes a new instance of the <see cref="SecurityException"/> class.
/// </summary> /// </summary>
/// <param name="message">The message that describes the error</param> /// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>
public SecurityException(string message, Exception innerException) public SecurityException(string message, Exception innerException)
: base(message, innerException) : base(message, innerException)

@ -166,7 +166,7 @@ namespace MediaBrowser.MediaEncoding.Encoder
/// Validates the supplied FQPN to ensure it is a ffmpeg utility. /// Validates the supplied FQPN to ensure it is a ffmpeg utility.
/// If checks pass, global variable FFmpegPath and EncoderLocation are updated. /// If checks pass, global variable FFmpegPath and EncoderLocation are updated.
/// </summary> /// </summary>
/// <param name="path">FQPN to test</param> /// <param name="path">FQPN to test.</param>
/// <param name="location">Location (External, Custom, System) of tool</param> /// <param name="location">Location (External, Custom, System) of tool</param>
/// <returns></returns> /// <returns></returns>
private bool ValidatePath(string path, FFmpegLocation location) private bool ValidatePath(string path, FFmpegLocation location)

@ -1065,23 +1065,43 @@ namespace MediaBrowser.MediaEncoding.Probing
// These support mulitple values, but for now we only store the first. // These support mulitple values, but for now we only store the first.
var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id")); var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID")); if (mb == null)
{
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
}
audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb); audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id")); mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID")); if (mb == null)
{
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
}
audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb); audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb);
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id")); mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID")); if (mb == null)
{
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
}
audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb); audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id")); mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID")); if (mb == null)
{
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
}
audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb); audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id")); mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID")); if (mb == null)
{
mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
}
audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb); audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb);
} }
@ -1364,14 +1384,18 @@ namespace MediaBrowser.MediaEncoding.Probing
description = string.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it description = string.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
} }
else else
{
throw new Exception(); // Switch to default parsing throw new Exception(); // Switch to default parsing
}
} }
catch // Default parsing catch // Default parsing
{ {
if (subtitle.Contains(".")) // skip the comment, keep the subtitle if (subtitle.Contains(".")) // skip the comment, keep the subtitle
description = string.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first description = string.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
else else
{
description = subtitle.Trim(); // Clean up whitespaces and save it description = subtitle.Trim(); // Clean up whitespaces and save it
}
} }
} }
} }

@ -58,7 +58,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles
var endTime = time[1]; var endTime = time[1];
var idx = endTime.IndexOf(" ", StringComparison.Ordinal); var idx = endTime.IndexOf(" ", StringComparison.Ordinal);
if (idx > 0) if (idx > 0)
{
endTime = endTime.Substring(0, idx); endTime = endTime.Substring(0, idx);
}
subEvent.EndPositionTicks = GetTicks(endTime); subEvent.EndPositionTicks = GetTicks(endTime);
var multiline = new List<string>(); var multiline = new List<string>();
while ((line = reader.ReadLine()) != null) while ((line = reader.ReadLine()) != null)

@ -41,7 +41,9 @@ namespace MediaBrowser.MediaEncoding.Subtitles
lineNumber++; lineNumber++;
if (!eventsStarted) if (!eventsStarted)
{
header.AppendLine(line); header.AppendLine(line);
}
if (line.Trim().ToLowerInvariant() == "[events]") if (line.Trim().ToLowerInvariant() == "[events]")
{ {
@ -62,17 +64,29 @@ namespace MediaBrowser.MediaEncoding.Subtitles
for (int i = 0; i < format.Length; i++) for (int i = 0; i < format.Length; i++)
{ {
if (format[i].Trim().ToLowerInvariant() == "layer") if (format[i].Trim().ToLowerInvariant() == "layer")
{
indexLayer = i; indexLayer = i;
}
else if (format[i].Trim().ToLowerInvariant() == "start") else if (format[i].Trim().ToLowerInvariant() == "start")
{
indexStart = i; indexStart = i;
}
else if (format[i].Trim().ToLowerInvariant() == "end") else if (format[i].Trim().ToLowerInvariant() == "end")
{
indexEnd = i; indexEnd = i;
}
else if (format[i].Trim().ToLowerInvariant() == "text") else if (format[i].Trim().ToLowerInvariant() == "text")
{
indexText = i; indexText = i;
}
else if (format[i].Trim().ToLowerInvariant() == "effect") else if (format[i].Trim().ToLowerInvariant() == "effect")
{
indexEffect = i; indexEffect = i;
}
else if (format[i].Trim().ToLowerInvariant() == "style") else if (format[i].Trim().ToLowerInvariant() == "style")
{
indexStyle = i; indexStyle = i;
}
} }
} }
} }
@ -89,28 +103,48 @@ namespace MediaBrowser.MediaEncoding.Subtitles
string[] splittedLine; string[] splittedLine;
if (s.StartsWith("dialogue:")) if (s.StartsWith("dialogue:"))
{
splittedLine = line.Substring(10).Split(','); splittedLine = line.Substring(10).Split(',');
}
else else
{
splittedLine = line.Split(','); splittedLine = line.Split(',');
}
for (int i = 0; i < splittedLine.Length; i++) for (int i = 0; i < splittedLine.Length; i++)
{ {
if (i == indexStart) if (i == indexStart)
{
start = splittedLine[i].Trim(); start = splittedLine[i].Trim();
}
else if (i == indexEnd) else if (i == indexEnd)
{
end = splittedLine[i].Trim(); end = splittedLine[i].Trim();
}
else if (i == indexLayer) else if (i == indexLayer)
{
layer = splittedLine[i]; layer = splittedLine[i];
}
else if (i == indexEffect) else if (i == indexEffect)
{
effect = splittedLine[i]; effect = splittedLine[i];
}
else if (i == indexText) else if (i == indexText)
{
text = splittedLine[i]; text = splittedLine[i];
}
else if (i == indexStyle) else if (i == indexStyle)
{
style = splittedLine[i]; style = splittedLine[i];
}
else if (i == indexName) else if (i == indexName)
{
name = splittedLine[i]; name = splittedLine[i];
}
else if (i > indexText) else if (i > indexText)
{
text += "," + splittedLine[i]; text += "," + splittedLine[i];
}
} }
try try
@ -169,15 +203,23 @@ namespace MediaBrowser.MediaEncoding.Subtitles
CheckAndAddSubTags(ref fontName, ref extraTags, out italic); CheckAndAddSubTags(ref fontName, ref extraTags, out italic);
text = text.Remove(start, end - start + 1); text = text.Remove(start, end - start + 1);
if (italic) if (italic)
{
text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + "><i>"); text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + "><i>");
}
else else
{
text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + ">"); text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + ">");
}
int indexOfEndTag = text.IndexOf("{\\fn}", start); int indexOfEndTag = text.IndexOf("{\\fn}", start);
if (indexOfEndTag > 0) if (indexOfEndTag > 0)
{
text = text.Remove(indexOfEndTag, "{\\fn}".Length).Insert(indexOfEndTag, "</font>"); text = text.Remove(indexOfEndTag, "{\\fn}".Length).Insert(indexOfEndTag, "</font>");
}
else else
{
text += "</font>"; text += "</font>";
}
} }
} }
@ -194,15 +236,23 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{ {
text = text.Remove(start, end - start + 1); text = text.Remove(start, end - start + 1);
if (italic) if (italic)
{
text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + "><i>"); text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + "><i>");
}
else else
{
text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + ">"); text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + ">");
}
int indexOfEndTag = text.IndexOf("{\\fs}", start); int indexOfEndTag = text.IndexOf("{\\fs}", start);
if (indexOfEndTag > 0) if (indexOfEndTag > 0)
{
text = text.Remove(indexOfEndTag, "{\\fs}".Length).Insert(indexOfEndTag, "</font>"); text = text.Remove(indexOfEndTag, "{\\fs}".Length).Insert(indexOfEndTag, "</font>");
}
else else
{
text += "</font>"; text += "</font>";
}
} }
} }
} }
@ -226,14 +276,22 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = text.Remove(start, end - start + 1); text = text.Remove(start, end - start + 1);
if (italic) if (italic)
{
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>"); text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
}
else else
{
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">"); text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
}
int indexOfEndTag = text.IndexOf("{\\c}", start); int indexOfEndTag = text.IndexOf("{\\c}", start);
if (indexOfEndTag > 0) if (indexOfEndTag > 0)
{
text = text.Remove(indexOfEndTag, "{\\c}".Length).Insert(indexOfEndTag, "</font>"); text = text.Remove(indexOfEndTag, "{\\c}".Length).Insert(indexOfEndTag, "</font>");
}
else else
{
text += "</font>"; text += "</font>";
}
} }
} }
@ -256,9 +314,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = text.Remove(start, end - start + 1); text = text.Remove(start, end - start + 1);
if (italic) if (italic)
{
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>"); text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
}
else else
{
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">"); text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
}
text += "</font>"; text += "</font>";
} }
} }
@ -268,19 +330,25 @@ namespace MediaBrowser.MediaEncoding.Subtitles
text = text.Replace(@"{\i0}", "</i>"); text = text.Replace(@"{\i0}", "</i>");
text = text.Replace(@"{\i}", "</i>"); text = text.Replace(@"{\i}", "</i>");
if (CountTagInText(text, "<i>") > CountTagInText(text, "</i>")) if (CountTagInText(text, "<i>") > CountTagInText(text, "</i>"))
{
text += "</i>"; text += "</i>";
}
text = text.Replace(@"{\u1}", "<u>"); text = text.Replace(@"{\u1}", "<u>");
text = text.Replace(@"{\u0}", "</u>"); text = text.Replace(@"{\u0}", "</u>");
text = text.Replace(@"{\u}", "</u>"); text = text.Replace(@"{\u}", "</u>");
if (CountTagInText(text, "<u>") > CountTagInText(text, "</u>")) if (CountTagInText(text, "<u>") > CountTagInText(text, "</u>"))
{
text += "</u>"; text += "</u>";
}
text = text.Replace(@"{\b1}", "<b>"); text = text.Replace(@"{\b1}", "<b>");
text = text.Replace(@"{\b0}", "</b>"); text = text.Replace(@"{\b0}", "</b>");
text = text.Replace(@"{\b}", "</b>"); text = text.Replace(@"{\b}", "</b>");
if (CountTagInText(text, "<b>") > CountTagInText(text, "</b>")) if (CountTagInText(text, "<b>") > CountTagInText(text, "</b>"))
{
text += "</b>"; text += "</b>";
}
return text; return text;
} }
@ -288,7 +356,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles
private static bool IsInteger(string s) private static bool IsInteger(string s)
{ {
if (int.TryParse(s, out var i)) if (int.TryParse(s, out var i))
{
return true; return true;
}
return false; return false;
} }
@ -300,7 +371,10 @@ namespace MediaBrowser.MediaEncoding.Subtitles
{ {
count++; count++;
if (index == text.Length) if (index == text.Length)
{
return count; return count;
}
index = text.IndexOf(tag, index + 1); index = text.IndexOf(tag, index + 1);
} }

@ -36,8 +36,11 @@ namespace MediaBrowser.Model.Configuration
public string EncoderPreset { get; set; } public string EncoderPreset { get; set; }
public string DeinterlaceMethod { get; set; } public string DeinterlaceMethod { get; set; }
public bool EnableDecodingColorDepth10Hevc { get; set; } public bool EnableDecodingColorDepth10Hevc { get; set; }
public bool EnableDecodingColorDepth10Vp9 { get; set; } public bool EnableDecodingColorDepth10Vp9 { get; set; }
public bool EnableHardwareEncoding { get; set; } public bool EnableHardwareEncoding { get; set; }
public bool EnableSubtitleExtraction { get; set; } public bool EnableSubtitleExtraction { get; set; }

@ -32,18 +32,25 @@ namespace MediaBrowser.Model.Dlna
} }
if (string.Equals(container, "avi", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "avi", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.AVI }; return new MediaFormatProfile[] { MediaFormatProfile.AVI };
}
if (string.Equals(container, "mkv", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "mkv", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.MATROSKA }; return new MediaFormatProfile[] { MediaFormatProfile.MATROSKA };
}
if (string.Equals(container, "mpeg2ps", StringComparison.OrdinalIgnoreCase) || if (string.Equals(container, "mpeg2ps", StringComparison.OrdinalIgnoreCase) ||
string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase)) string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.MPEG_PS_NTSC, MediaFormatProfile.MPEG_PS_PAL }; return new MediaFormatProfile[] { MediaFormatProfile.MPEG_PS_NTSC, MediaFormatProfile.MPEG_PS_PAL };
}
if (string.Equals(container, "mpeg1video", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "mpeg1video", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.MPEG1 }; return new MediaFormatProfile[] { MediaFormatProfile.MPEG1 };
}
if (string.Equals(container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) || if (string.Equals(container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
string.Equals(container, "mpegts", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "mpegts", StringComparison.OrdinalIgnoreCase) ||
@ -54,10 +61,14 @@ namespace MediaBrowser.Model.Dlna
} }
if (string.Equals(container, "flv", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "flv", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.FLV }; return new MediaFormatProfile[] { MediaFormatProfile.FLV };
}
if (string.Equals(container, "wtv", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "wtv", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.WTV }; return new MediaFormatProfile[] { MediaFormatProfile.WTV };
}
if (string.Equals(container, "3gp", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "3gp", StringComparison.OrdinalIgnoreCase))
{ {
@ -66,7 +77,9 @@ namespace MediaBrowser.Model.Dlna
} }
if (string.Equals(container, "ogv", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "ogv", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.OGV }; return new MediaFormatProfile[] { MediaFormatProfile.OGV };
}
return Array.Empty<MediaFormatProfile>(); return Array.Empty<MediaFormatProfile>();
} }
@ -111,7 +124,9 @@ namespace MediaBrowser.Model.Dlna
if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{ {
if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_50_LPCM_T }; return new MediaFormatProfile[] { MediaFormatProfile.AVC_TS_HD_50_LPCM_T };
}
if (string.Equals(audioCodec, "dts", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "dts", StringComparison.OrdinalIgnoreCase))
{ {
@ -134,14 +149,20 @@ namespace MediaBrowser.Model.Dlna
} }
if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AAC_MULT5{1}", resolution, suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AAC_MULT5{1}", resolution, suffix)) };
}
if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_MPEG1_L3{1}", resolution, suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_MPEG1_L3{1}", resolution, suffix)) };
}
if (string.IsNullOrEmpty(audioCodec) || if (string.IsNullOrEmpty(audioCodec) ||
string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AC3{1}", resolution, suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("AVC_TS_MP_{0}D_AC3{1}", resolution, suffix)) };
}
} }
else if (string.Equals(videoCodec, "vc1", StringComparison.OrdinalIgnoreCase)) else if (string.Equals(videoCodec, "vc1", StringComparison.OrdinalIgnoreCase))
{ {
@ -165,13 +186,24 @@ namespace MediaBrowser.Model.Dlna
else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase)) else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{ {
if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AAC{0}", suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AAC{0}", suffix)) };
}
if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG1_L3{0}", suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG1_L3{0}", suffix)) };
}
if (string.Equals(audioCodec, "mp2", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "mp2", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG2_L2{0}", suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_MPEG2_L2{0}", suffix)) };
}
if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
{
return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AC3{0}", suffix)) }; return new MediaFormatProfile[] { ValueOf(string.Format("MPEG4_P2_TS_ASP_AC3{0}", suffix)) };
}
} }
return new MediaFormatProfile[] { }; return new MediaFormatProfile[] { };
@ -187,7 +219,10 @@ namespace MediaBrowser.Model.Dlna
if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{ {
if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "lpcm", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_MP4_LPCM; return MediaFormatProfile.AVC_MP4_LPCM;
}
if (string.IsNullOrEmpty(audioCodec) || if (string.IsNullOrEmpty(audioCodec) ||
string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)) string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
{ {
@ -204,12 +239,16 @@ namespace MediaBrowser.Model.Dlna
if ((width.Value <= 720) && (height.Value <= 576)) if ((width.Value <= 720) && (height.Value <= 576))
{ {
if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_MP4_MP_SD_AAC_MULT5; return MediaFormatProfile.AVC_MP4_MP_SD_AAC_MULT5;
}
} }
else if ((width.Value <= 1280) && (height.Value <= 720)) else if ((width.Value <= 1280) && (height.Value <= 720))
{ {
if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_MP4_MP_HD_720p_AAC; return MediaFormatProfile.AVC_MP4_MP_HD_720p_AAC;
}
} }
else if ((width.Value <= 1920) && (height.Value <= 1080)) else if ((width.Value <= 1920) && (height.Value <= 1080))
{ {
@ -226,7 +265,10 @@ namespace MediaBrowser.Model.Dlna
if (width.HasValue && height.HasValue && width.Value <= 720 && height.Value <= 576) if (width.HasValue && height.HasValue && width.Value <= 720 && height.Value <= 576)
{ {
if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_P2_MP4_ASP_AAC; return MediaFormatProfile.MPEG4_P2_MP4_ASP_AAC;
}
if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase) || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase) || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
{ {
return MediaFormatProfile.MPEG4_P2_MP4_NDSD; return MediaFormatProfile.MPEG4_P2_MP4_NDSD;
@ -250,15 +292,22 @@ namespace MediaBrowser.Model.Dlna
if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{ {
if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.AVC_3GPP_BL_QCIF15_AAC; return MediaFormatProfile.AVC_3GPP_BL_QCIF15_AAC;
}
} }
else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) || else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase) ||
string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase)) string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
{ {
if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(audioCodec) || string.Equals(audioCodec, "wma", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AAC; return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AAC;
}
if (string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase)) if (string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AMR; return MediaFormatProfile.MPEG4_P2_3GPP_SP_L0B_AMR;
}
} }
else if (string.Equals(videoCodec, "h263", StringComparison.OrdinalIgnoreCase) && string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase)) else if (string.Equals(videoCodec, "h263", StringComparison.OrdinalIgnoreCase) && string.Equals(audioCodec, "amrnb", StringComparison.OrdinalIgnoreCase))
{ {
@ -300,11 +349,19 @@ namespace MediaBrowser.Model.Dlna
if (width.HasValue && height.HasValue) if (width.HasValue && height.HasValue)
{ {
if ((width.Value <= 720) && (height.Value <= 576)) if ((width.Value <= 720) && (height.Value <= 576))
{
return MediaFormatProfile.VC1_ASF_AP_L1_WMA; return MediaFormatProfile.VC1_ASF_AP_L1_WMA;
}
if ((width.Value <= 1280) && (height.Value <= 720)) if ((width.Value <= 1280) && (height.Value <= 720))
{
return MediaFormatProfile.VC1_ASF_AP_L2_WMA; return MediaFormatProfile.VC1_ASF_AP_L2_WMA;
}
if ((width.Value <= 1920) && (height.Value <= 1080)) if ((width.Value <= 1920) && (height.Value <= 1080))
{
return MediaFormatProfile.VC1_ASF_AP_L3_WMA; return MediaFormatProfile.VC1_ASF_AP_L3_WMA;
}
} }
} }
else if (string.Equals(videoCodec, "mpeg2video", StringComparison.OrdinalIgnoreCase)) else if (string.Equals(videoCodec, "mpeg2video", StringComparison.OrdinalIgnoreCase))
@ -318,27 +375,41 @@ namespace MediaBrowser.Model.Dlna
public MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels) public MediaFormatProfile? ResolveAudioFormat(string container, int? bitrate, int? frequency, int? channels)
{ {
if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase))
{
return ResolveAudioASFFormat(bitrate); return ResolveAudioASFFormat(bitrate);
}
if (string.Equals(container, "mp3", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "mp3", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.MP3; return MediaFormatProfile.MP3;
}
if (string.Equals(container, "lpcm", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "lpcm", StringComparison.OrdinalIgnoreCase))
{
return ResolveAudioLPCMFormat(frequency, channels); return ResolveAudioLPCMFormat(frequency, channels);
}
if (string.Equals(container, "mp4", StringComparison.OrdinalIgnoreCase) || if (string.Equals(container, "mp4", StringComparison.OrdinalIgnoreCase) ||
string.Equals(container, "aac", StringComparison.OrdinalIgnoreCase)) string.Equals(container, "aac", StringComparison.OrdinalIgnoreCase))
{
return ResolveAudioMP4Format(bitrate); return ResolveAudioMP4Format(bitrate);
}
if (string.Equals(container, "adts", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "adts", StringComparison.OrdinalIgnoreCase))
{
return ResolveAudioADTSFormat(bitrate); return ResolveAudioADTSFormat(bitrate);
}
if (string.Equals(container, "flac", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "flac", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.FLAC; return MediaFormatProfile.FLAC;
}
if (string.Equals(container, "oga", StringComparison.OrdinalIgnoreCase) || if (string.Equals(container, "oga", StringComparison.OrdinalIgnoreCase) ||
string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase)) string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.OGG; return MediaFormatProfile.OGG;
}
return null; return null;
} }
@ -410,13 +481,19 @@ namespace MediaBrowser.Model.Dlna
return ResolveImageJPGFormat(width, height); return ResolveImageJPGFormat(width, height);
if (string.Equals(container, "png", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "png", StringComparison.OrdinalIgnoreCase))
{
return ResolveImagePNGFormat(width, height); return ResolveImagePNGFormat(width, height);
}
if (string.Equals(container, "gif", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "gif", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.GIF_LRG; return MediaFormatProfile.GIF_LRG;
}
if (string.Equals(container, "raw", StringComparison.OrdinalIgnoreCase)) if (string.Equals(container, "raw", StringComparison.OrdinalIgnoreCase))
{
return MediaFormatProfile.RAW; return MediaFormatProfile.RAW;
}
return null; return null;
} }
@ -426,10 +503,14 @@ namespace MediaBrowser.Model.Dlna
if (width.HasValue && height.HasValue) if (width.HasValue && height.HasValue)
{ {
if ((width.Value <= 160) && (height.Value <= 160)) if ((width.Value <= 160) && (height.Value <= 160))
{
return MediaFormatProfile.JPEG_TN; return MediaFormatProfile.JPEG_TN;
}
if ((width.Value <= 640) && (height.Value <= 480)) if ((width.Value <= 640) && (height.Value <= 480))
{
return MediaFormatProfile.JPEG_SM; return MediaFormatProfile.JPEG_SM;
}
if ((width.Value <= 1024) && (height.Value <= 768)) if ((width.Value <= 1024) && (height.Value <= 768))
{ {
@ -447,7 +528,9 @@ namespace MediaBrowser.Model.Dlna
if (width.HasValue && height.HasValue) if (width.HasValue && height.HasValue)
{ {
if ((width.Value <= 160) && (height.Value <= 160)) if ((width.Value <= 160) && (height.Value <= 160))
{
return MediaFormatProfile.PNG_TN; return MediaFormatProfile.PNG_TN;
}
} }
return MediaFormatProfile.PNG_LRG; return MediaFormatProfile.PNG_LRG;

@ -384,7 +384,10 @@ namespace MediaBrowser.Model.Dlna
audioCodecProfiles.Add(i); audioCodecProfiles.Add(i);
} }
if (audioCodecProfiles.Count >= 1) break; if (audioCodecProfiles.Count >= 1)
{
break;
}
} }
var audioTranscodingConditions = new List<ProfileCondition>(); var audioTranscodingConditions = new List<ProfileCondition>();

@ -421,7 +421,10 @@ namespace MediaBrowser.Model.Entities
{ {
get get
{ {
if (Type != MediaStreamType.Subtitle) return false; if (Type != MediaStreamType.Subtitle)
{
return false;
}
if (string.IsNullOrEmpty(Codec) && !IsExternal) if (string.IsNullOrEmpty(Codec) && !IsExternal)
{ {

@ -124,8 +124,8 @@ namespace MediaBrowser.Model.Services
/// Gets or sets a query parameter value by name. A query may contain multiple values of the same name /// Gets or sets a query parameter value by name. A query may contain multiple values of the same name
/// (i.e. "x=1&amp;x=2"), in which case the value is an array, which works for both getting and setting. /// (i.e. "x=1&amp;x=2"), in which case the value is an array, which works for both getting and setting.
/// </summary> /// </summary>
/// <param name="name">The query parameter name</param> /// <param name="name">The query parameter name.</param>
/// <returns>The query parameter value or array of values</returns> /// <returns>The query parameter value or array of values.</returns>
public string this[string name] public string this[string name]
{ {
get => Get(name); get => Get(name);

@ -128,9 +128,21 @@ namespace MediaBrowser.Model.Services
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(null, obj))
if (ReferenceEquals(this, obj)) return true; {
if (obj.GetType() != this.GetType()) return false; return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return Equals((RouteAttribute)obj); return Equals((RouteAttribute)obj);
} }

@ -113,7 +113,10 @@ namespace MediaBrowser.Providers.Manager
foreach (var imageType in images) foreach (var imageType in images)
{ {
if (!IsEnabled(savedOptions, imageType, item)) continue; if (!IsEnabled(savedOptions, imageType, item))
{
continue;
}
if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType))) if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
{ {

@ -391,7 +391,7 @@ namespace MediaBrowser.Providers.Manager
{ {
if (!child.IsFolder) if (!child.IsFolder)
{ {
ticks += (child.RunTimeTicks ?? 0); ticks += child.RunTimeTicks ?? 0;
} }
} }

@ -159,7 +159,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.BoxSets
{ {
var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false); var mainResult = await FetchMainResult(tmdbId, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
if (mainResult == null) return; if (mainResult == null)
{
return;
}
var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage); var dataFilePath = GetDataFilePath(_config.ApplicationPaths, tmdbId, preferredMetadataLanguage);

@ -194,7 +194,10 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
{ {
var mainResult = await FetchMainResult(id, true, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false); var mainResult = await FetchMainResult(id, true, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
if (mainResult == null) return; if (mainResult == null)
{
return;
}
var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage); var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
@ -312,7 +315,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
/// <param name="id">The id.</param> /// <param name="id">The id.</param>
/// <param name="isTmdbId">if set to <c>true</c> [is TMDB identifier].</param> /// <param name="isTmdbId">if set to <c>true</c> [is TMDB identifier].</param>
/// <param name="language">The language.</param> /// <param name="language">The language.</param>
/// <param name="cancellationToken">The cancellation token</param> /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{CompleteMovieData}.</returns> /// <returns>Task{CompleteMovieData}.</returns>
internal async Task<MovieResult> FetchMainResult(string id, bool isTmdbId, string language, CancellationToken cancellationToken) internal async Task<MovieResult> FetchMainResult(string id, bool isTmdbId, string language, CancellationToken cancellationToken)
{ {

@ -10,14 +10,9 @@ namespace Rssdp
{ {
public IPAddress LocalIpAddress { get; set; } public IPAddress LocalIpAddress { get; set; }
#region Fields
private readonly DiscoveredSsdpDevice _DiscoveredDevice; private readonly DiscoveredSsdpDevice _DiscoveredDevice;
private readonly bool _IsNewlyDiscovered;
#endregion private readonly bool _IsNewlyDiscovered;
#region Constructors
/// <summary> /// <summary>
/// Full constructor. /// Full constructor.
@ -27,16 +22,15 @@ namespace Rssdp
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="discoveredDevice"/> parameter is null.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="discoveredDevice"/> parameter is null.</exception>
public DeviceAvailableEventArgs(DiscoveredSsdpDevice discoveredDevice, bool isNewlyDiscovered) public DeviceAvailableEventArgs(DiscoveredSsdpDevice discoveredDevice, bool isNewlyDiscovered)
{ {
if (discoveredDevice == null) throw new ArgumentNullException(nameof(discoveredDevice)); if (discoveredDevice == null)
{
throw new ArgumentNullException(nameof(discoveredDevice));
}
_DiscoveredDevice = discoveredDevice; _DiscoveredDevice = discoveredDevice;
_IsNewlyDiscovered = isNewlyDiscovered; _IsNewlyDiscovered = isNewlyDiscovered;
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Returns true if the device was discovered due to an alive notification, or a search and was not already in the cache. Returns false if the item came from the cache but matched the current search request. /// Returns true if the device was discovered due to an alive notification, or a search and was not already in the cache. Returns false if the item came from the cache but matched the current search request.
/// </summary> /// </summary>
@ -52,7 +46,5 @@ namespace Rssdp
{ {
get { return _DiscoveredDevice; } get { return _DiscoveredDevice; }
} }
#endregion
} }
} }

@ -7,15 +7,8 @@ namespace Rssdp
/// </summary> /// </summary>
public sealed class DeviceEventArgs : EventArgs public sealed class DeviceEventArgs : EventArgs
{ {
#region Fields
private readonly SsdpDevice _Device; private readonly SsdpDevice _Device;
#endregion
#region Constructors
/// <summary> /// <summary>
/// Constructs a new instance for the specified <see cref="SsdpDevice"/>. /// Constructs a new instance for the specified <see cref="SsdpDevice"/>.
/// </summary> /// </summary>
@ -23,15 +16,14 @@ namespace Rssdp
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
public DeviceEventArgs(SsdpDevice device) public DeviceEventArgs(SsdpDevice device)
{ {
if (device == null) throw new ArgumentNullException(nameof(device)); if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
_Device = device; _Device = device;
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Returns the <see cref="SsdpDevice"/> instance the event being raised for. /// Returns the <see cref="SsdpDevice"/> instance the event being raised for.
/// </summary> /// </summary>
@ -39,7 +31,5 @@ namespace Rssdp
{ {
get { return _Device; } get { return _Device; }
} }
#endregion
} }
} }

@ -7,15 +7,9 @@ namespace Rssdp
/// </summary> /// </summary>
public sealed class DeviceUnavailableEventArgs : EventArgs public sealed class DeviceUnavailableEventArgs : EventArgs
{ {
#region Fields
private readonly DiscoveredSsdpDevice _DiscoveredDevice; private readonly DiscoveredSsdpDevice _DiscoveredDevice;
private readonly bool _Expired;
#endregion
#region Constructors private readonly bool _Expired;
/// <summary> /// <summary>
/// Full constructor. /// Full constructor.
@ -25,16 +19,15 @@ namespace Rssdp
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="discoveredDevice"/> parameter is null.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="discoveredDevice"/> parameter is null.</exception>
public DeviceUnavailableEventArgs(DiscoveredSsdpDevice discoveredDevice, bool expired) public DeviceUnavailableEventArgs(DiscoveredSsdpDevice discoveredDevice, bool expired)
{ {
if (discoveredDevice == null) throw new ArgumentNullException(nameof(discoveredDevice)); if (discoveredDevice == null)
{
throw new ArgumentNullException(nameof(discoveredDevice));
}
_DiscoveredDevice = discoveredDevice; _DiscoveredDevice = discoveredDevice;
_Expired = expired; _Expired = expired;
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Returns true if the device is considered unavailable because it's cached information expired before a new alive notification or search result was received. Returns false if the device is unavailable because it sent an explicit notification of it's unavailability. /// Returns true if the device is considered unavailable because it's cached information expired before a new alive notification or search result was received. Returns false if the device is unavailable because it sent an explicit notification of it's unavailability.
/// </summary> /// </summary>
@ -50,7 +43,5 @@ namespace Rssdp
{ {
get { return _DiscoveredDevice; } get { return _DiscoveredDevice; }
} }
#endregion
} }
} }

@ -10,15 +10,8 @@ namespace Rssdp
/// <seealso cref="Infrastructure.ISsdpDeviceLocator"/> /// <seealso cref="Infrastructure.ISsdpDeviceLocator"/>
public sealed class DiscoveredSsdpDevice public sealed class DiscoveredSsdpDevice
{ {
#region Fields
private DateTimeOffset _AsAt; private DateTimeOffset _AsAt;
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Sets or returns the type of notification, being either a uuid, device type, service type or upnp:rootdevice. /// Sets or returns the type of notification, being either a uuid, device type, service type or upnp:rootdevice.
/// </summary> /// </summary>
@ -60,10 +53,6 @@ namespace Rssdp
/// </summary> /// </summary>
public HttpHeaders ResponseHeaders { get; set; } public HttpHeaders ResponseHeaders { get; set; }
#endregion
#region Public Methods
/// <summary> /// <summary>
/// Returns true if this device information has expired, based on the current date/time, and the <see cref="CacheLifetime"/> &amp; <see cref="AsAt"/> properties. /// Returns true if this device information has expired, based on the current date/time, and the <see cref="CacheLifetime"/> &amp; <see cref="AsAt"/> properties.
/// </summary> /// </summary>
@ -73,10 +62,6 @@ namespace Rssdp
return this.CacheLifetime == TimeSpan.Zero || this.AsAt.Add(this.CacheLifetime) <= DateTimeOffset.Now; return this.CacheLifetime == TimeSpan.Zero || this.AsAt.Add(this.CacheLifetime) <= DateTimeOffset.Now;
} }
#endregion
#region Overrides
/// <summary> /// <summary>
/// Returns the device's <see cref="Usn"/> value. /// Returns the device's <see cref="Usn"/> value.
/// </summary> /// </summary>
@ -85,7 +70,5 @@ namespace Rssdp
{ {
return this.Usn; return this.Usn;
} }
#endregion
} }
} }

@ -9,9 +9,6 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public abstract class DisposableManagedObjectBase : IDisposable public abstract class DisposableManagedObjectBase : IDisposable
{ {
#region Public Methods
/// <summary> /// <summary>
/// Override this method and dispose any objects you own the lifetime of if disposing is true; /// Override this method and dispose any objects you own the lifetime of if disposing is true;
/// </summary> /// </summary>
@ -26,13 +23,12 @@ namespace Rssdp.Infrastructure
/// <seealso cref="Dispose()"/> /// <seealso cref="Dispose()"/>
protected virtual void ThrowIfDisposed() protected virtual void ThrowIfDisposed()
{ {
if (this.IsDisposed) throw new ObjectDisposedException(this.GetType().FullName); if (this.IsDisposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Sets or returns a boolean indicating whether or not this instance has been disposed. /// Sets or returns a boolean indicating whether or not this instance has been disposed.
/// </summary> /// </summary>
@ -43,8 +39,6 @@ namespace Rssdp.Infrastructure
private set; private set;
} }
#endregion
public string BuildMessage(string header, Dictionary<string, string> values) public string BuildMessage(string header, Dictionary<string, string> values)
{ {
var builder = new StringBuilder(); var builder = new StringBuilder();
@ -63,8 +57,6 @@ namespace Rssdp.Infrastructure
return builder.ToString(); return builder.ToString();
} }
#region IDisposable Members
/// <summary> /// <summary>
/// Disposes this object instance and all internally managed resources. /// Disposes this object instance and all internally managed resources.
/// </summary> /// </summary>
@ -79,7 +71,5 @@ namespace Rssdp.Infrastructure
Dispose(true); Dispose(true);
} }
#endregion
} }
} }

@ -11,16 +11,9 @@ namespace Rssdp.Infrastructure
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public abstract class HttpParserBase<T> where T : new() public abstract class HttpParserBase<T> where T : new()
{ {
#region Fields
private readonly string[] LineTerminators = new string[] { "\r\n", "\n" }; private readonly string[] LineTerminators = new string[] { "\r\n", "\n" };
private readonly char[] SeparatorCharacters = new char[] { ',', ';' }; private readonly char[] SeparatorCharacters = new char[] { ',', ';' };
#endregion
#region Public Methods
/// <summary> /// <summary>
/// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object. /// Parses the <paramref name="data"/> provided into either a <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> object.
/// </summary> /// </summary>
@ -38,9 +31,20 @@ namespace Rssdp.Infrastructure
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Honestly, it's fine. MemoryStream doesn't mind.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Honestly, it's fine. MemoryStream doesn't mind.")]
protected virtual void Parse(T message, System.Net.Http.Headers.HttpHeaders headers, string data) protected virtual void Parse(T message, System.Net.Http.Headers.HttpHeaders headers, string data)
{ {
if (data == null) throw new ArgumentNullException(nameof(data)); if (data == null)
if (data.Length == 0) throw new ArgumentException("data cannot be an empty string.", nameof(data)); {
if (!LineTerminators.Any(data.Contains)) throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data)); throw new ArgumentNullException(nameof(data));
}
if (data.Length == 0)
{
throw new ArgumentException("data cannot be an empty string.", nameof(data));
}
if (!LineTerminators.Any(data.Contains))
{
throw new ArgumentException("data is not a valid request, it does not contain any CRLF/LF terminators.", nameof(data));
}
using (var retVal = new ByteArrayContent(Array.Empty<byte>())) using (var retVal = new ByteArrayContent(Array.Empty<byte>()))
{ {
@ -73,18 +77,20 @@ namespace Rssdp.Infrastructure
/// <returns>A <see cref="Version"/> object containing the parsed version data.</returns> /// <returns>A <see cref="Version"/> object containing the parsed version data.</returns>
protected Version ParseHttpVersion(string versionData) protected Version ParseHttpVersion(string versionData)
{ {
if (versionData == null) throw new ArgumentNullException(nameof(versionData)); if (versionData == null)
{
throw new ArgumentNullException(nameof(versionData));
}
var versionSeparatorIndex = versionData.IndexOf('/'); var versionSeparatorIndex = versionData.IndexOf('/');
if (versionSeparatorIndex <= 0 || versionSeparatorIndex == versionData.Length) throw new ArgumentException("request header line is invalid. Http Version not supplied or incorrect format.", nameof(versionData)); if (versionSeparatorIndex <= 0 || versionSeparatorIndex == versionData.Length)
{
throw new ArgumentException("request header line is invalid. Http Version not supplied or incorrect format.", nameof(versionData));
}
return Version.Parse(versionData.Substring(versionSeparatorIndex + 1)); return Version.Parse(versionData.Substring(versionSeparatorIndex + 1));
} }
#endregion
#region Private Methods
/// <summary> /// <summary>
/// Parses a line from an HTTP request or response message containing a header name and value pair. /// Parses a line from an HTTP request or response message containing a header name and value pair.
/// </summary> /// </summary>
@ -108,9 +114,13 @@ namespace Rssdp.Infrastructure
var headersToAddTo = IsContentHeader(headerName) ? contentHeaders : headers; var headersToAddTo = IsContentHeader(headerName) ? contentHeaders : headers;
if (values.Count > 1) if (values.Count > 1)
{
headersToAddTo.TryAddWithoutValidation(headerName, values); headersToAddTo.TryAddWithoutValidation(headerName, values);
}
else else
{
headersToAddTo.TryAddWithoutValidation(headerName, values.First()); headersToAddTo.TryAddWithoutValidation(headerName, values.First());
}
} }
private int ParseHeaders(System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HttpHeaders contentHeaders, string[] lines) private int ParseHeaders(System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HttpHeaders contentHeaders, string[] lines)
@ -130,7 +140,9 @@ namespace Rssdp.Infrastructure
lineIndex++; lineIndex++;
} }
else else
{
break; break;
}
} }
ParseHeader(line, headers, contentHeaders); ParseHeader(line, headers, contentHeaders);
@ -154,7 +166,9 @@ namespace Rssdp.Infrastructure
var indexOfSeparator = headerValue.IndexOfAny(SeparatorCharacters); var indexOfSeparator = headerValue.IndexOfAny(SeparatorCharacters);
if (indexOfSeparator <= 0) if (indexOfSeparator <= 0)
{
values.Add(headerValue); values.Add(headerValue);
}
else else
{ {
var segments = headerValue.Split(SeparatorCharacters); var segments = headerValue.Split(SeparatorCharacters);
@ -164,13 +178,17 @@ namespace Rssdp.Infrastructure
{ {
var segment = segments[segmentIndex]; var segment = segments[segmentIndex];
if (segment.Trim().StartsWith("\"", StringComparison.OrdinalIgnoreCase)) if (segment.Trim().StartsWith("\"", StringComparison.OrdinalIgnoreCase))
{
segment = CombineQuotedSegments(segments, ref segmentIndex, segment); segment = CombineQuotedSegments(segments, ref segmentIndex, segment);
}
values.Add(segment); values.Add(segment);
} }
} }
else else
{
values.AddRange(segments); values.AddRange(segments);
}
} }
return values; return values;
@ -193,17 +211,20 @@ namespace Rssdp.Infrastructure
} }
if (index + 1 < segments.Length) if (index + 1 < segments.Length)
{
trimmedSegment += "," + segments[index + 1].TrimEnd(); trimmedSegment += "," + segments[index + 1].TrimEnd();
}
} }
segmentIndex = segments.Length; segmentIndex = segments.Length;
if (trimmedSegment.StartsWith("\"", StringComparison.OrdinalIgnoreCase) && trimmedSegment.EndsWith("\"", StringComparison.OrdinalIgnoreCase)) if (trimmedSegment.StartsWith("\"", StringComparison.OrdinalIgnoreCase) && trimmedSegment.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
{
return trimmedSegment.Substring(1, trimmedSegment.Length - 2); return trimmedSegment.Substring(1, trimmedSegment.Length - 2);
}
else else
{
return trimmedSegment; return trimmedSegment;
}
} }
#endregion
} }
} }

@ -9,17 +9,10 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public sealed class HttpRequestParser : HttpParserBase<HttpRequestMessage> public sealed class HttpRequestParser : HttpParserBase<HttpRequestMessage>
{ {
#region Fields & Constants
private readonly string[] ContentHeaderNames = new string[] private readonly string[] ContentHeaderNames = new string[]
{ {
"Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified" "Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
}; };
#endregion
#region Public Methods
/// <summary> /// <summary>
/// Parses the specified data into a <see cref="HttpRequestMessage"/> instance. /// Parses the specified data into a <see cref="HttpRequestMessage"/> instance.
@ -41,14 +34,12 @@ namespace Rssdp.Infrastructure
finally finally
{ {
if (retVal != null) if (retVal != null)
{
retVal.Dispose(); retVal.Dispose();
}
} }
} }
#endregion
#region Overrides
/// <summary> /// <summary>
/// Used to parse the first line of an HTTP request or response and assign the values to the appropriate properties on the <paramref name="message"/>. /// Used to parse the first line of an HTTP request or response and assign the values to the appropriate properties on the <paramref name="message"/>.
/// </summary> /// </summary>
@ -56,18 +47,32 @@ namespace Rssdp.Infrastructure
/// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param> /// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param>
protected override void ParseStatusLine(string data, HttpRequestMessage message) protected override void ParseStatusLine(string data, HttpRequestMessage message)
{ {
if (data == null) throw new ArgumentNullException(nameof(data)); if (data == null)
if (message == null) throw new ArgumentNullException(nameof(message)); {
throw new ArgumentNullException(nameof(data));
}
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
var parts = data.Split(' '); var parts = data.Split(' ');
if (parts.Length < 2) throw new ArgumentException("Status line is invalid. Insufficient status parts.", nameof(data)); if (parts.Length < 2)
{
throw new ArgumentException("Status line is invalid. Insufficient status parts.", nameof(data));
}
message.Method = new HttpMethod(parts[0].Trim()); message.Method = new HttpMethod(parts[0].Trim());
Uri requestUri; Uri requestUri;
if (Uri.TryCreate(parts[1].Trim(), UriKind.RelativeOrAbsolute, out requestUri)) if (Uri.TryCreate(parts[1].Trim(), UriKind.RelativeOrAbsolute, out requestUri))
{
message.RequestUri = requestUri; message.RequestUri = requestUri;
}
else else
{
System.Diagnostics.Debug.WriteLine(parts[1]); System.Diagnostics.Debug.WriteLine(parts[1]);
}
if (parts.Length >= 3) if (parts.Length >= 3)
{ {
@ -83,7 +88,5 @@ namespace Rssdp.Infrastructure
{ {
return ContentHeaderNames.Contains(headerName, StringComparer.OrdinalIgnoreCase); return ContentHeaderNames.Contains(headerName, StringComparer.OrdinalIgnoreCase);
} }
#endregion
} }
} }

@ -10,17 +10,10 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public sealed class HttpResponseParser : HttpParserBase<HttpResponseMessage> public sealed class HttpResponseParser : HttpParserBase<HttpResponseMessage>
{ {
#region Fields & Constants
private readonly string[] ContentHeaderNames = new string[] private readonly string[] ContentHeaderNames = new string[]
{ {
"Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified" "Allow", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-Length", "Content-Location", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Last-Modified"
}; };
#endregion
#region Public Methods
/// <summary> /// <summary>
/// Parses the specified data into a <see cref="HttpResponseMessage"/> instance. /// Parses the specified data into a <see cref="HttpResponseMessage"/> instance.
@ -41,16 +34,14 @@ namespace Rssdp.Infrastructure
catch catch
{ {
if (retVal != null) if (retVal != null)
{
retVal.Dispose(); retVal.Dispose();
}
throw; throw;
} }
} }
#endregion
#region Overrides Methods
/// <summary> /// <summary>
/// Returns a boolean indicating whether the specified HTTP header name represents a content header (true), or a message header (false). /// Returns a boolean indicating whether the specified HTTP header name represents a content header (true), or a message header (false).
/// </summary> /// </summary>
@ -68,17 +59,29 @@ namespace Rssdp.Infrastructure
/// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param> /// <param name="message">Either a <see cref="HttpResponseMessage"/> or <see cref="HttpRequestMessage"/> to assign the parsed values to.</param>
protected override void ParseStatusLine(string data, HttpResponseMessage message) protected override void ParseStatusLine(string data, HttpResponseMessage message)
{ {
if (data == null) throw new ArgumentNullException(nameof(data)); if (data == null)
if (message == null) throw new ArgumentNullException(nameof(message)); {
throw new ArgumentNullException(nameof(data));
}
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
var parts = data.Split(' '); var parts = data.Split(' ');
if (parts.Length < 2) throw new ArgumentException("data status line is invalid. Insufficient status parts.", nameof(data)); if (parts.Length < 2)
{
throw new ArgumentException("data status line is invalid. Insufficient status parts.", nameof(data));
}
message.Version = ParseHttpVersion(parts[0].Trim()); message.Version = ParseHttpVersion(parts[0].Trim());
int statusCode = -1; int statusCode = -1;
if (!Int32.TryParse(parts[1].Trim(), out statusCode)) if (!Int32.TryParse(parts[1].Trim(), out statusCode))
{
throw new ArgumentException("data status line is invalid. Status code is not a valid integer.", nameof(data)); throw new ArgumentException("data status line is invalid. Status code is not a valid integer.", nameof(data));
}
message.StatusCode = (HttpStatusCode)statusCode; message.StatusCode = (HttpStatusCode)statusCode;
@ -87,7 +90,5 @@ namespace Rssdp.Infrastructure
message.ReasonPhrase = parts[2].Trim(); message.ReasonPhrase = parts[2].Trim();
} }
} }
#endregion
} }
} }

@ -8,8 +8,15 @@ namespace Rssdp.Infrastructure
{ {
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector) public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{ {
if (source == null) throw new ArgumentNullException(nameof(source)); if (source == null)
if (selector == null) throw new ArgumentNullException(nameof(selector)); {
throw new ArgumentNullException(nameof(source));
}
if (selector == null)
{
throw new ArgumentNullException(nameof(selector));
}
return !source.Any() ? source : return !source.Any() ? source :
source.Concat( source.Concat(

@ -10,9 +10,6 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public interface ISsdpCommunicationsServer : IDisposable public interface ISsdpCommunicationsServer : IDisposable
{ {
#region Events
/// <summary> /// <summary>
/// Raised when a HTTPU request message is received by a socket (unicast or multicast). /// Raised when a HTTPU request message is received by a socket (unicast or multicast).
/// </summary> /// </summary>
@ -23,10 +20,6 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
event EventHandler<ResponseReceivedEventArgs> ResponseReceived; event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
#endregion
#region Methods
/// <summary> /// <summary>
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
/// </summary> /// </summary>
@ -48,10 +41,6 @@ namespace Rssdp.Infrastructure
Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
#endregion
#region Properties
/// <summary> /// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances. /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
/// </summary> /// </summary>
@ -59,7 +48,5 @@ namespace Rssdp.Infrastructure
/// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocatorBase"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para> /// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocatorBase"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para>
/// </remarks> /// </remarks>
bool IsShared { get; set; } bool IsShared { get; set; }
#endregion
} }
} }

@ -13,9 +13,6 @@ namespace Rssdp.Infrastructure
/// <seealso cref="ISsdpDevicePublisher"/> /// <seealso cref="ISsdpDevicePublisher"/>
public interface ISsdpDeviceLocator public interface ISsdpDeviceLocator
{ {
#region Events
/// <summary> /// <summary>
/// Event raised when a device becomes available or is found by a search request. /// Event raised when a device becomes available or is found by a search request.
/// </summary> /// </summary>
@ -34,10 +31,6 @@ namespace Rssdp.Infrastructure
/// <seealso cref="StopListeningForNotifications"/> /// <seealso cref="StopListeningForNotifications"/>
event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable; event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable;
#endregion
#region Properties
/// <summary> /// <summary>
/// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="DeviceAvailable"/> or <see cref="DeviceUnavailable"/> events. /// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="DeviceAvailable"/> or <see cref="DeviceUnavailable"/> events.
/// </summary> /// </summary>
@ -58,12 +51,6 @@ namespace Rssdp.Infrastructure
set; set;
} }
#endregion
#region Methods
#region SearchAsync Overloads
/// <summary> /// <summary>
/// Aynchronously performs a search for all devices using the default search timeout, and returns an awaitable task that can be used to retrieve the results. /// Aynchronously performs a search for all devices using the default search timeout, and returns an awaitable task that can be used to retrieve the results.
/// </summary> /// </summary>
@ -108,8 +95,6 @@ namespace Rssdp.Infrastructure
/// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns> /// <returns>A task whose result is an <see cref="System.Collections.Generic.IEnumerable{T}"/> of <see cref="DiscoveredSsdpDevice" /> instances, representing all found devices.</returns>
System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync(TimeSpan searchWaitTime); System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<DiscoveredSsdpDevice>> SearchAsync(TimeSpan searchWaitTime);
#endregion
/// <summary> /// <summary>
/// Starts listening for broadcast notifications of service availability. /// Starts listening for broadcast notifications of service availability.
/// </summary> /// </summary>
@ -134,8 +119,5 @@ namespace Rssdp.Infrastructure
/// <seealso cref="DeviceUnavailable"/> /// <seealso cref="DeviceUnavailable"/>
/// <seealso cref="NotificationFilter"/> /// <seealso cref="NotificationFilter"/>
void StopListeningForNotifications(); void StopListeningForNotifications();
#endregion
} }
} }

@ -9,17 +9,12 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public sealed class RequestReceivedEventArgs : EventArgs public sealed class RequestReceivedEventArgs : EventArgs
{ {
#region Fields
private readonly HttpRequestMessage _Message; private readonly HttpRequestMessage _Message;
private readonly IPEndPoint _ReceivedFrom;
#endregion private readonly IPEndPoint _ReceivedFrom;
public IPAddress LocalIpAddress { get; private set; } public IPAddress LocalIpAddress { get; private set; }
#region Constructors
/// <summary> /// <summary>
/// Full constructor. /// Full constructor.
/// </summary> /// </summary>
@ -30,10 +25,6 @@ namespace Rssdp.Infrastructure
LocalIpAddress = localIpAddress; LocalIpAddress = localIpAddress;
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// The <see cref="HttpRequestMessage"/> that was received. /// The <see cref="HttpRequestMessage"/> that was received.
/// </summary> /// </summary>
@ -49,7 +40,5 @@ namespace Rssdp.Infrastructure
{ {
get { return _ReceivedFrom; } get { return _ReceivedFrom; }
} }
#endregion
} }
} }

@ -9,17 +9,11 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public sealed class ResponseReceivedEventArgs : EventArgs public sealed class ResponseReceivedEventArgs : EventArgs
{ {
public IPAddress LocalIpAddress { get; set; } public IPAddress LocalIpAddress { get; set; }
#region Fields
private readonly HttpResponseMessage _Message; private readonly HttpResponseMessage _Message;
private readonly IPEndPoint _ReceivedFrom;
#endregion
#region Constructors private readonly IPEndPoint _ReceivedFrom;
/// <summary> /// <summary>
/// Full constructor. /// Full constructor.
@ -30,10 +24,6 @@ namespace Rssdp.Infrastructure
_ReceivedFrom = receivedFrom; _ReceivedFrom = receivedFrom;
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// The <see cref="HttpResponseMessage"/> that was received. /// The <see cref="HttpResponseMessage"/> that was received.
/// </summary> /// </summary>
@ -49,7 +39,5 @@ namespace Rssdp.Infrastructure
{ {
get { return _ReceivedFrom; } get { return _ReceivedFrom; }
} }
#endregion
} }
} }

@ -19,9 +19,6 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
{ {
#region Fields
/* We could technically use one socket listening on port 1900 for everything. /* We could technically use one socket listening on port 1900 for everything.
* This should get both multicast (notifications) and unicast (search response) messages, however * This should get both multicast (notifications) and unicast (search response) messages, however
* this often doesn't work under Windows because the MS SSDP service is running. If that service * this often doesn't work under Windows because the MS SSDP service is running. If that service
@ -55,10 +52,6 @@ namespace Rssdp.Infrastructure
private bool _IsShared; private bool _IsShared;
private readonly bool _enableMultiSocketBinding; private readonly bool _enableMultiSocketBinding;
#endregion
#region Events
/// <summary> /// <summary>
/// Raised when a HTTPU request message is received by a socket (unicast or multicast). /// Raised when a HTTPU request message is received by a socket (unicast or multicast).
/// </summary> /// </summary>
@ -69,10 +62,6 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public event EventHandler<ResponseReceivedEventArgs> ResponseReceived; public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
#endregion
#region Constructors
/// <summary> /// <summary>
/// Minimum constructor. /// Minimum constructor.
/// </summary> /// </summary>
@ -91,8 +80,15 @@ namespace Rssdp.Infrastructure
/// <exception cref="ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding) public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
{ {
if (socketFactory == null) throw new ArgumentNullException(nameof(socketFactory)); if (socketFactory == null)
if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero."); {
throw new ArgumentNullException(nameof(socketFactory));
}
if (multicastTimeToLive <= 0)
{
throw new ArgumentOutOfRangeException(nameof(multicastTimeToLive), "multicastTimeToLive must be greater than zero.");
}
_BroadcastListenSocketSynchroniser = new object(); _BroadcastListenSocketSynchroniser = new object();
_SendSocketSynchroniser = new object(); _SendSocketSynchroniser = new object();
@ -109,10 +105,6 @@ namespace Rssdp.Infrastructure
_enableMultiSocketBinding = enableMultiSocketBinding; _enableMultiSocketBinding = enableMultiSocketBinding;
} }
#endregion
#region Public Methods
/// <summary> /// <summary>
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
/// </summary> /// </summary>
@ -166,7 +158,10 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{ {
if (messageData == null) throw new ArgumentNullException(nameof(messageData)); if (messageData == null)
{
throw new ArgumentNullException(nameof(messageData));
}
ThrowIfDisposed(); ThrowIfDisposed();
@ -249,7 +244,10 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{ {
if (message == null) throw new ArgumentNullException(nameof(message)); if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
byte[] messageData = Encoding.UTF8.GetBytes(message); byte[] messageData = Encoding.UTF8.GetBytes(message);
@ -298,10 +296,6 @@ namespace Rssdp.Infrastructure
} }
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances. /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
/// </summary> /// </summary>
@ -315,10 +309,6 @@ namespace Rssdp.Infrastructure
set { _IsShared = value; } set { _IsShared = value; }
} }
#endregion
#region Overrides
/// <summary> /// <summary>
/// Stops listening for requests, disposes this instance and all internal resources. /// Stops listening for requests, disposes this instance and all internal resources.
/// </summary> /// </summary>
@ -333,10 +323,6 @@ namespace Rssdp.Infrastructure
} }
} }
#endregion
#region Private Methods
private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
{ {
var sockets = _sendSockets; var sockets = _sendSockets;
@ -494,20 +480,21 @@ namespace Rssdp.Infrastructure
var handlers = this.RequestReceived; var handlers = this.RequestReceived;
if (handlers != null) if (handlers != null)
{
handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress)); handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
}
} }
private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress) private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress)
{ {
var handlers = this.ResponseReceived; var handlers = this.ResponseReceived;
if (handlers != null) if (handlers != null)
{
handlers(this, new ResponseReceivedEventArgs(data, endPoint) handlers(this, new ResponseReceivedEventArgs(data, endPoint)
{ {
LocalIpAddress = localIpAddress LocalIpAddress = localIpAddress
}); });
}
} }
#endregion
} }
} }

@ -15,9 +15,6 @@ namespace Rssdp
/// <seealso cref="SsdpEmbeddedDevice"/> /// <seealso cref="SsdpEmbeddedDevice"/>
public abstract class SsdpDevice public abstract class SsdpDevice
{ {
#region Fields
private string _Udn; private string _Udn;
private string _DeviceType; private string _DeviceType;
private string _DeviceTypeNamespace; private string _DeviceTypeNamespace;
@ -25,10 +22,6 @@ namespace Rssdp
private IList<SsdpDevice> _Devices; private IList<SsdpDevice> _Devices;
#endregion
#region Events
/// <summary> /// <summary>
/// Raised when a new child device is added. /// Raised when a new child device is added.
/// </summary> /// </summary>
@ -43,10 +36,6 @@ namespace Rssdp
/// <seealso cref="DeviceRemoved"/> /// <seealso cref="DeviceRemoved"/>
public event EventHandler<DeviceEventArgs> DeviceRemoved; public event EventHandler<DeviceEventArgs> DeviceRemoved;
#endregion
#region Constructors
/// <summary> /// <summary>
/// Derived type constructor, allows constructing a device with no parent. Should only be used from derived types that are or inherit from <see cref="SsdpRootDevice"/>. /// Derived type constructor, allows constructing a device with no parent. Should only be used from derived types that are or inherit from <see cref="SsdpRootDevice"/>.
/// </summary> /// </summary>
@ -60,23 +49,19 @@ namespace Rssdp
this.Devices = new ReadOnlyCollection<SsdpDevice>(_Devices); this.Devices = new ReadOnlyCollection<SsdpDevice>(_Devices);
} }
#endregion
public SsdpRootDevice ToRootDevice() public SsdpRootDevice ToRootDevice()
{ {
var device = this; var device = this;
var rootDevice = device as SsdpRootDevice; var rootDevice = device as SsdpRootDevice;
if (rootDevice == null) if (rootDevice == null)
{
rootDevice = ((SsdpEmbeddedDevice)device).RootDevice; rootDevice = ((SsdpEmbeddedDevice)device).RootDevice;
}
return rootDevice; return rootDevice;
} }
#region Public Properties
#region UPnP Device Description Properties
/// <summary> /// <summary>
/// Sets or returns the core device type (not including namespace, version etc.). Required. /// Sets or returns the core device type (not including namespace, version etc.). Required.
/// </summary> /// </summary>
@ -180,9 +165,13 @@ namespace Rssdp
get get
{ {
if (String.IsNullOrEmpty(_Udn) && !String.IsNullOrEmpty(this.Uuid)) if (String.IsNullOrEmpty(_Udn) && !String.IsNullOrEmpty(this.Uuid))
{
return "uuid:" + this.Uuid; return "uuid:" + this.Uuid;
}
else else
{
return _Udn; return _Udn;
}
} }
set set
@ -252,8 +241,6 @@ namespace Rssdp
/// </remarks> /// </remarks>
public Uri PresentationUrl { get; set; } public Uri PresentationUrl { get; set; }
#endregion
/// <summary> /// <summary>
/// Returns a read-only enumerable set of <see cref="SsdpDevice"/> objects representing children of this device. Child devices are optional. /// Returns a read-only enumerable set of <see cref="SsdpDevice"/> objects representing children of this device. Child devices are optional.
/// </summary> /// </summary>
@ -265,10 +252,6 @@ namespace Rssdp
private set; private set;
} }
#endregion
#region Public Methods
/// <summary> /// <summary>
/// Adds a child device to the <see cref="Devices"/> collection. /// Adds a child device to the <see cref="Devices"/> collection.
/// </summary> /// </summary>
@ -282,9 +265,20 @@ namespace Rssdp
/// <seealso cref="DeviceAdded"/> /// <seealso cref="DeviceAdded"/>
public void AddDevice(SsdpEmbeddedDevice device) public void AddDevice(SsdpEmbeddedDevice device)
{ {
if (device == null) throw new ArgumentNullException(nameof(device)); if (device == null)
if (device.RootDevice != null && device.RootDevice != this.ToRootDevice()) throw new InvalidOperationException("This device is already associated with a different root device (has been added as a child in another branch)."); {
if (device == this) throw new InvalidOperationException("Can't add device to itself."); throw new ArgumentNullException(nameof(device));
}
if (device.RootDevice != null && device.RootDevice != this.ToRootDevice())
{
throw new InvalidOperationException("This device is already associated with a different root device (has been added as a child in another branch).");
}
if (device == this)
{
throw new InvalidOperationException("Can't add device to itself.");
}
bool wasAdded = false; bool wasAdded = false;
lock (_Devices) lock (_Devices)
@ -295,7 +289,9 @@ namespace Rssdp
} }
if (wasAdded) if (wasAdded)
{
OnDeviceAdded(device); OnDeviceAdded(device);
}
} }
/// <summary> /// <summary>
@ -310,7 +306,10 @@ namespace Rssdp
/// <seealso cref="DeviceRemoved"/> /// <seealso cref="DeviceRemoved"/>
public void RemoveDevice(SsdpEmbeddedDevice device) public void RemoveDevice(SsdpEmbeddedDevice device)
{ {
if (device == null) throw new ArgumentNullException(nameof(device)); if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
bool wasRemoved = false; bool wasRemoved = false;
lock (_Devices) lock (_Devices)
@ -323,7 +322,9 @@ namespace Rssdp
} }
if (wasRemoved) if (wasRemoved)
{
OnDeviceRemoved(device); OnDeviceRemoved(device);
}
} }
/// <summary> /// <summary>
@ -336,7 +337,9 @@ namespace Rssdp
{ {
var handlers = this.DeviceAdded; var handlers = this.DeviceAdded;
if (handlers != null) if (handlers != null)
{
handlers(this, new DeviceEventArgs(device)); handlers(this, new DeviceEventArgs(device));
}
} }
/// <summary> /// <summary>
@ -349,9 +352,9 @@ namespace Rssdp
{ {
var handlers = this.DeviceRemoved; var handlers = this.DeviceRemoved;
if (handlers != null) if (handlers != null)
{
handlers(this, new DeviceEventArgs(device)); handlers(this, new DeviceEventArgs(device));
}
} }
#endregion
} }
} }

@ -13,9 +13,6 @@ namespace Rssdp.Infrastructure
/// </summary> /// </summary>
public class SsdpDeviceLocator : DisposableManagedObjectBase public class SsdpDeviceLocator : DisposableManagedObjectBase
{ {
#region Fields & Constants
private List<DiscoveredSsdpDevice> _Devices; private List<DiscoveredSsdpDevice> _Devices;
private ISsdpCommunicationsServer _CommunicationsServer; private ISsdpCommunicationsServer _CommunicationsServer;
@ -25,16 +22,15 @@ namespace Rssdp.Infrastructure
private readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4); private readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4);
private readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1); private readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
#endregion
#region Constructors
/// <summary> /// <summary>
/// Default constructor. /// Default constructor.
/// </summary> /// </summary>
public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer) public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer)
{ {
if (communicationsServer == null) throw new ArgumentNullException(nameof(communicationsServer)); if (communicationsServer == null)
{
throw new ArgumentNullException(nameof(communicationsServer));
}
_CommunicationsServer = communicationsServer; _CommunicationsServer = communicationsServer;
_CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived;
@ -42,10 +38,6 @@ namespace Rssdp.Infrastructure
_Devices = new List<DiscoveredSsdpDevice>(); _Devices = new List<DiscoveredSsdpDevice>();
} }
#endregion
#region Events
/// <summary> /// <summary>
/// Raised for when /// Raised for when
/// <list type="bullet"> /// <list type="bullet">
@ -76,12 +68,6 @@ namespace Rssdp.Infrastructure
/// <seealso cref="StopListeningForNotifications"/> /// <seealso cref="StopListeningForNotifications"/>
public event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable; public event EventHandler<DeviceUnavailableEventArgs> DeviceUnavailable;
#endregion
#region Public Methods
#region Search Overloads
public void RestartBroadcastTimer(TimeSpan dueTime, TimeSpan period) public void RestartBroadcastTimer(TimeSpan dueTime, TimeSpan period)
{ {
lock (_timerLock) lock (_timerLock)
@ -157,18 +143,31 @@ namespace Rssdp.Infrastructure
private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken) private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken)
{ {
if (searchTarget == null) throw new ArgumentNullException(nameof(searchTarget)); if (searchTarget == null)
if (searchTarget.Length == 0) throw new ArgumentException("searchTarget cannot be an empty string.", nameof(searchTarget)); {
if (searchWaitTime.TotalSeconds < 0) throw new ArgumentException("searchWaitTime must be a positive time."); throw new ArgumentNullException(nameof(searchTarget));
if (searchWaitTime.TotalSeconds > 0 && searchWaitTime.TotalSeconds <= 1) throw new ArgumentException("searchWaitTime must be zero (if you are not using the result and relying entirely in the events), or greater than one second."); }
if (searchTarget.Length == 0)
{
throw new ArgumentException("searchTarget cannot be an empty string.", nameof(searchTarget));
}
if (searchWaitTime.TotalSeconds < 0)
{
throw new ArgumentException("searchWaitTime must be a positive time.");
}
if (searchWaitTime.TotalSeconds > 0 && searchWaitTime.TotalSeconds <= 1)
{
throw new ArgumentException("searchWaitTime must be zero (if you are not using the result and relying entirely in the events), or greater than one second.");
}
ThrowIfDisposed(); ThrowIfDisposed();
return BroadcastDiscoverMessage(searchTarget, SearchTimeToMXValue(searchWaitTime), cancellationToken); return BroadcastDiscoverMessage(searchTarget, SearchTimeToMXValue(searchWaitTime), cancellationToken);
} }
#endregion
/// <summary> /// <summary>
/// Starts listening for broadcast notifications of service availability. /// Starts listening for broadcast notifications of service availability.
/// </summary> /// </summary>
@ -211,14 +210,19 @@ namespace Rssdp.Infrastructure
/// <seealso cref="DeviceAvailable"/> /// <seealso cref="DeviceAvailable"/>
protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress localIpAddress) protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress localIpAddress)
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
var handlers = this.DeviceAvailable; var handlers = this.DeviceAvailable;
if (handlers != null) if (handlers != null)
{
handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) handlers(this, new DeviceAvailableEventArgs(device, isNewDevice)
{ {
LocalIpAddress = localIpAddress LocalIpAddress = localIpAddress
}); });
}
} }
/// <summary> /// <summary>
@ -229,17 +233,18 @@ namespace Rssdp.Infrastructure
/// <seealso cref="DeviceUnavailable"/> /// <seealso cref="DeviceUnavailable"/>
protected virtual void OnDeviceUnavailable(DiscoveredSsdpDevice device, bool expired) protected virtual void OnDeviceUnavailable(DiscoveredSsdpDevice device, bool expired)
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
var handlers = this.DeviceUnavailable; var handlers = this.DeviceUnavailable;
if (handlers != null) if (handlers != null)
{
handlers(this, new DeviceUnavailableEventArgs(device, expired)); handlers(this, new DeviceUnavailableEventArgs(device, expired));
}
} }
#endregion
#region Public Properties
/// <summary> /// <summary>
/// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="ISsdpDeviceLocator.DeviceAvailable"/> or <see cref="ISsdpDeviceLocator.DeviceUnavailable"/> events. /// Sets or returns a string containing the filter for notifications. Notifications not matching the filter will not raise the <see cref="ISsdpDeviceLocator.DeviceAvailable"/> or <see cref="ISsdpDeviceLocator.DeviceUnavailable"/> events.
/// </summary> /// </summary>
@ -261,10 +266,6 @@ namespace Rssdp.Infrastructure
set; set;
} }
#endregion
#region Overrides
/// <summary> /// <summary>
/// Disposes this object and all internal resources. Stops listening for all network messages. /// Disposes this object and all internal resources. Stops listening for all network messages.
/// </summary> /// </summary>
@ -285,12 +286,6 @@ namespace Rssdp.Infrastructure
} }
} }
#endregion
#region Private Methods
#region Discovery/Device Add
private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress localIpAddress) private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress localIpAddress)
{ {
bool isNewDevice = false; bool isNewDevice = false;
@ -314,7 +309,10 @@ namespace Rssdp.Infrastructure
private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress localIpAddress) private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress localIpAddress)
{ {
if (!NotificationTypeMatchesFilter(device)) return; if (!NotificationTypeMatchesFilter(device))
{
return;
}
OnDeviceAvailable(device, isNewDevice, localIpAddress); OnDeviceAvailable(device, isNewDevice, localIpAddress);
} }
@ -326,10 +324,6 @@ namespace Rssdp.Infrastructure
|| device.NotificationType == this.NotificationFilter; || device.NotificationType == this.NotificationFilter;
} }
#endregion
#region Network Message Processing
private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken) private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken)
{ {
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
@ -355,7 +349,10 @@ namespace Rssdp.Infrastructure
private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress localIpAddress) private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress localIpAddress)
{ {
if (!message.IsSuccessStatusCode) return; if (!message.IsSuccessStatusCode)
{
return;
}
var location = GetFirstHeaderUriValue("Location", message); var location = GetFirstHeaderUriValue("Location", message);
if (location != null) if (location != null)
@ -376,13 +373,20 @@ namespace Rssdp.Infrastructure
private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress localIpAddress) private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress localIpAddress)
{ {
if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) return; if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0)
{
return;
}
var notificationType = GetFirstHeaderStringValue("NTS", message); var notificationType = GetFirstHeaderStringValue("NTS", message);
if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0) if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0)
{
ProcessAliveNotification(message, localIpAddress); ProcessAliveNotification(message, localIpAddress);
}
else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0) else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0)
{
ProcessByeByeNotification(message); ProcessByeByeNotification(message);
}
} }
private void ProcessAliveNotification(HttpRequestMessage message, IPAddress localIpAddress) private void ProcessAliveNotification(HttpRequestMessage message, IPAddress localIpAddress)
@ -424,13 +428,13 @@ namespace Rssdp.Infrastructure
}; };
if (NotificationTypeMatchesFilter(deadDevice)) if (NotificationTypeMatchesFilter(deadDevice))
{
OnDeviceUnavailable(deadDevice, false); OnDeviceUnavailable(deadDevice, false);
}
} }
} }
} }
#region Header/Message Processing Utilities
private string GetFirstHeaderStringValue(string headerName, HttpResponseMessage message) private string GetFirstHeaderStringValue(string headerName, HttpResponseMessage message)
{ {
string retVal = null; string retVal = null;
@ -439,7 +443,9 @@ namespace Rssdp.Infrastructure
{ {
message.Headers.TryGetValues(headerName, out values); message.Headers.TryGetValues(headerName, out values);
if (values != null) if (values != null)
{
retVal = values.FirstOrDefault(); retVal = values.FirstOrDefault();
}
} }
return retVal; return retVal;
@ -453,7 +459,9 @@ namespace Rssdp.Infrastructure
{ {
message.Headers.TryGetValues(headerName, out values); message.Headers.TryGetValues(headerName, out values);
if (values != null) if (values != null)
{
retVal = values.FirstOrDefault(); retVal = values.FirstOrDefault();
}
} }
return retVal; return retVal;
@ -467,7 +475,9 @@ namespace Rssdp.Infrastructure
{ {
request.Headers.TryGetValues(headerName, out values); request.Headers.TryGetValues(headerName, out values);
if (values != null) if (values != null)
{
value = values.FirstOrDefault(); value = values.FirstOrDefault();
}
} }
Uri retVal; Uri retVal;
@ -483,7 +493,9 @@ namespace Rssdp.Infrastructure
{ {
response.Headers.TryGetValues(headerName, out values); response.Headers.TryGetValues(headerName, out values);
if (values != null) if (values != null)
{
value = values.FirstOrDefault(); value = values.FirstOrDefault();
}
} }
Uri retVal; Uri retVal;
@ -493,20 +505,20 @@ namespace Rssdp.Infrastructure
private TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue) private TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue)
{ {
if (headerValue == null) return TimeSpan.Zero; if (headerValue == null)
{
return TimeSpan.Zero;
}
return (TimeSpan)(headerValue.MaxAge ?? headerValue.SharedMaxAge ?? TimeSpan.Zero); return (TimeSpan)(headerValue.MaxAge ?? headerValue.SharedMaxAge ?? TimeSpan.Zero);
} }
#endregion
#endregion
#region Expiry and Device Removal
private void RemoveExpiredDevicesFromCache() private void RemoveExpiredDevicesFromCache()
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
DiscoveredSsdpDevice[] expiredDevices = null; DiscoveredSsdpDevice[] expiredDevices = null;
lock (_Devices) lock (_Devices)
@ -515,7 +527,10 @@ namespace Rssdp.Infrastructure
foreach (var device in expiredDevices) foreach (var device in expiredDevices)
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
_Devices.Remove(device); _Devices.Remove(device);
} }
@ -526,7 +541,10 @@ namespace Rssdp.Infrastructure
// problems. // problems.
foreach (var expiredUsn in (from expiredDevice in expiredDevices select expiredDevice.Usn).Distinct()) foreach (var expiredUsn in (from expiredDevice in expiredDevices select expiredDevice.Usn).Distinct())
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
DeviceDied(expiredUsn, true); DeviceDied(expiredUsn, true);
} }
@ -540,7 +558,10 @@ namespace Rssdp.Infrastructure
existingDevices = FindExistingDeviceNotifications(_Devices, deviceUsn); existingDevices = FindExistingDeviceNotifications(_Devices, deviceUsn);
foreach (var existingDevice in existingDevices) foreach (var existingDevice in existingDevices)
{ {
if (this.IsDisposed) return true; if (this.IsDisposed)
{
return true;
}
_Devices.Remove(existingDevice); _Devices.Remove(existingDevice);
} }
@ -551,7 +572,9 @@ namespace Rssdp.Infrastructure
foreach (var removedDevice in existingDevices) foreach (var removedDevice in existingDevices)
{ {
if (NotificationTypeMatchesFilter(removedDevice)) if (NotificationTypeMatchesFilter(removedDevice))
{
OnDeviceUnavailable(removedDevice, expired); OnDeviceUnavailable(removedDevice, expired);
}
} }
return true; return true;
@ -560,14 +583,16 @@ namespace Rssdp.Infrastructure
return false; return false;
} }
#endregion
private TimeSpan SearchTimeToMXValue(TimeSpan searchWaitTime) private TimeSpan SearchTimeToMXValue(TimeSpan searchWaitTime)
{ {
if (searchWaitTime.TotalSeconds < 2 || searchWaitTime == TimeSpan.Zero) if (searchWaitTime.TotalSeconds < 2 || searchWaitTime == TimeSpan.Zero)
{
return OneSecond; return OneSecond;
}
else else
{
return searchWaitTime.Subtract(OneSecond); return searchWaitTime.Subtract(OneSecond);
}
} }
private DiscoveredSsdpDevice FindExistingDeviceNotification(IEnumerable<DiscoveredSsdpDevice> devices, string notificationType, string usn) private DiscoveredSsdpDevice FindExistingDeviceNotification(IEnumerable<DiscoveredSsdpDevice> devices, string notificationType, string usn)
@ -598,10 +623,6 @@ namespace Rssdp.Infrastructure
return list; return list;
} }
#endregion
#region Event Handlers
private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e) private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e)
{ {
ProcessSearchResponseMessage(e.Message, e.LocalIpAddress); ProcessSearchResponseMessage(e.Message, e.LocalIpAddress);
@ -611,7 +632,5 @@ namespace Rssdp.Infrastructure
{ {
ProcessNotificationMessage(e.Message, e.LocalIpAddress); ProcessNotificationMessage(e.Message, e.LocalIpAddress);
} }
#endregion
} }
} }

@ -40,12 +40,35 @@ namespace Rssdp.Infrastructure
public SsdpDevicePublisher(ISsdpCommunicationsServer communicationsServer, INetworkManager networkManager, public SsdpDevicePublisher(ISsdpCommunicationsServer communicationsServer, INetworkManager networkManager,
string osName, string osVersion, bool sendOnlyMatchedHost) string osName, string osVersion, bool sendOnlyMatchedHost)
{ {
if (communicationsServer == null) throw new ArgumentNullException(nameof(communicationsServer)); if (communicationsServer == null)
if (networkManager == null) throw new ArgumentNullException(nameof(networkManager)); {
if (osName == null) throw new ArgumentNullException(nameof(osName)); throw new ArgumentNullException(nameof(communicationsServer));
if (osName.Length == 0) throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); }
if (osVersion == null) throw new ArgumentNullException(nameof(osVersion));
if (osVersion.Length == 0) throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); if (networkManager == null)
{
throw new ArgumentNullException(nameof(networkManager));
}
if (osName == null)
{
throw new ArgumentNullException(nameof(osName));
}
if (osName.Length == 0)
{
throw new ArgumentException("osName cannot be an empty string.", nameof(osName));
}
if (osVersion == null)
{
throw new ArgumentNullException(nameof(osVersion));
}
if (osVersion.Length == 0)
{
throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName));
}
_SupportPnpRootDevice = true; _SupportPnpRootDevice = true;
_Devices = new List<SsdpRootDevice>(); _Devices = new List<SsdpRootDevice>();
@ -82,7 +105,10 @@ namespace Rssdp.Infrastructure
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable supresses compiler warning, but task is not really needed.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable supresses compiler warning, but task is not really needed.")]
public void AddDevice(SsdpRootDevice device) public void AddDevice(SsdpRootDevice device)
{ {
if (device == null) throw new ArgumentNullException(nameof(device)); if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
ThrowIfDisposed(); ThrowIfDisposed();
@ -115,7 +141,10 @@ namespace Rssdp.Infrastructure
/// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
public async Task RemoveDevice(SsdpRootDevice device) public async Task RemoveDevice(SsdpRootDevice device)
{ {
if (device == null) throw new ArgumentNullException(nameof(device)); if (device == null)
{
throw new ArgumentNullException(nameof(device));
}
bool wasRemoved = false; bool wasRemoved = false;
lock (_Devices) lock (_Devices)
@ -186,7 +215,9 @@ namespace Rssdp.Infrastructure
if (commsServer != null) if (commsServer != null)
{ {
if (!commsServer.IsShared) if (!commsServer.IsShared)
{
commsServer.Dispose(); commsServer.Dispose();
}
} }
_RecentSearchRequests = null; _RecentSearchRequests = null;
@ -227,10 +258,15 @@ namespace Rssdp.Infrastructure
// return; // return;
} }
if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0) return; if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0)
{
return;
}
if (maxWaitInterval > 120) if (maxWaitInterval > 120)
{
maxWaitInterval = _Random.Next(0, 120); maxWaitInterval = _Random.Next(0, 120);
}
// Do not block synchronously as that may tie up a threadpool thread for several seconds. // Do not block synchronously as that may tie up a threadpool thread for several seconds.
Task.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) => Task.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) =>
@ -240,13 +276,21 @@ namespace Rssdp.Infrastructure
lock (_Devices) lock (_Devices)
{ {
if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0) if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)
{
devices = GetAllDevicesAsFlatEnumerable().ToArray(); devices = GetAllDevicesAsFlatEnumerable().ToArray();
}
else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (this.SupportPnpRootDevice && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)) else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (this.SupportPnpRootDevice && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0))
{
devices = _Devices.ToArray(); devices = _Devices.ToArray();
}
else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase)) else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
{
devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray(); devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
}
else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase)) else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
{
devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray(); devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
}
} }
if (devices != null) if (devices != null)
@ -286,7 +330,9 @@ namespace Rssdp.Infrastructure
{ {
SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
if (this.SupportPnpRootDevice) if (this.SupportPnpRootDevice)
{
SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
}
} }
SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken); SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken);
@ -352,15 +398,21 @@ namespace Rssdp.Infrastructure
{ {
var lastRequest = _RecentSearchRequests[newRequest.Key]; var lastRequest = _RecentSearchRequests[newRequest.Key];
if (lastRequest.IsOld()) if (lastRequest.IsOld())
{
_RecentSearchRequests[newRequest.Key] = newRequest; _RecentSearchRequests[newRequest.Key] = newRequest;
}
else else
{
isDuplicateRequest = true; isDuplicateRequest = true;
}
} }
else else
{ {
_RecentSearchRequests.Add(newRequest.Key, newRequest); _RecentSearchRequests.Add(newRequest.Key, newRequest);
if (_RecentSearchRequests.Count > 10) if (_RecentSearchRequests.Count > 10)
{
CleanUpRecentSearchRequestsAsync(); CleanUpRecentSearchRequestsAsync();
}
} }
} }
@ -382,7 +434,10 @@ namespace Rssdp.Infrastructure
{ {
try try
{ {
if (IsDisposed) return; if (IsDisposed)
{
return;
}
// WriteTrace("Begin Sending Alive Notifications For All Devices"); // WriteTrace("Begin Sending Alive Notifications For All Devices");
@ -394,7 +449,10 @@ namespace Rssdp.Infrastructure
foreach (var device in devices) foreach (var device in devices)
{ {
if (IsDisposed) return; if (IsDisposed)
{
return;
}
SendAliveNotifications(device, true, CancellationToken.None); SendAliveNotifications(device, true, CancellationToken.None);
} }
@ -414,7 +472,9 @@ namespace Rssdp.Infrastructure
{ {
SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken); SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken);
if (this.SupportPnpRootDevice) if (this.SupportPnpRootDevice)
{
SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), cancellationToken); SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), cancellationToken);
}
} }
SendAliveNotification(device, device.Udn, device.Udn, cancellationToken); SendAliveNotification(device, device.Udn, device.Udn, cancellationToken);
@ -458,7 +518,9 @@ namespace Rssdp.Infrastructure
{ {
tasks.Add(SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken)); tasks.Add(SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), cancellationToken));
if (this.SupportPnpRootDevice) if (this.SupportPnpRootDevice)
{
tasks.Add(SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"), cancellationToken)); tasks.Add(SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"), cancellationToken));
}
} }
tasks.Add(SendByeByeNotification(device, device.Udn, device.Udn, cancellationToken)); tasks.Add(SendByeByeNotification(device, device.Udn, device.Udn, cancellationToken));
@ -499,20 +561,27 @@ namespace Rssdp.Infrastructure
var timer = _RebroadcastAliveNotificationsTimer; var timer = _RebroadcastAliveNotificationsTimer;
_RebroadcastAliveNotificationsTimer = null; _RebroadcastAliveNotificationsTimer = null;
if (timer != null) if (timer != null)
{
timer.Dispose(); timer.Dispose();
}
} }
private TimeSpan GetMinimumNonZeroCacheLifetime() private TimeSpan GetMinimumNonZeroCacheLifetime()
{ {
var nonzeroCacheLifetimesQuery = (from device var nonzeroCacheLifetimesQuery = (
in _Devices from device
where device.CacheLifetime != TimeSpan.Zero in _Devices
select device.CacheLifetime).ToList(); where device.CacheLifetime != TimeSpan.Zero
select device.CacheLifetime).ToList();
if (nonzeroCacheLifetimesQuery.Any()) if (nonzeroCacheLifetimesQuery.Any())
{
return nonzeroCacheLifetimesQuery.Min(); return nonzeroCacheLifetimesQuery.Min();
}
else else
{
return TimeSpan.Zero; return TimeSpan.Zero;
}
} }
private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName) private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
@ -520,7 +589,9 @@ namespace Rssdp.Infrastructure
string retVal = null; string retVal = null;
IEnumerable<String> values = null; IEnumerable<String> values = null;
if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null) if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null)
{
retVal = values.FirstOrDefault(); retVal = values.FirstOrDefault();
}
return retVal; return retVal;
} }
@ -540,14 +611,21 @@ namespace Rssdp.Infrastructure
{ {
var rootDevice = device as SsdpRootDevice; var rootDevice = device as SsdpRootDevice;
if (rootDevice != null) if (rootDevice != null)
{
WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location); WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
}
else else
{
WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid); WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid);
}
} }
private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e) private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
if (string.Equals(e.Message.Method.Method, SsdpConstants.MSearchMethod, StringComparison.OrdinalIgnoreCase)) if (string.Equals(e.Message.Method.Method, SsdpConstants.MSearchMethod, StringComparison.OrdinalIgnoreCase))
{ {

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save