fix SA1503 for one line if statements

This commit is contained in:
telans 2020-06-20 20:35:29 +12:00
parent 8e3d874802
commit 98db8f72e0
No known key found for this signature in database
GPG key ID: 195444EE92DBCB20
64 changed files with 843 additions and 193 deletions

View file

@ -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);
}
} }
} }
} }

View file

@ -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)

View file

@ -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);

View file

@ -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);
} }

View file

@ -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();

View file

@ -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;
} }

View file

@ -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
{ {

View file

@ -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);

View file

@ -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;");
} }

View file

@ -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;

View file

@ -63,7 +63,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;
} }

View file

@ -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)

View file

@ -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();
} }

View file

@ -34,13 +34,25 @@ namespace Jellyfin.Data.Entities
/// <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>();

View file

@ -32,12 +32,20 @@ namespace Jellyfin.Data.Entities
/// <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);

View file

@ -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();
} }

View file

@ -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>();

View file

@ -31,15 +31,26 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -30,15 +30,26 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -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>();

View file

@ -31,15 +31,26 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -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();
} }

View file

@ -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();
} }

View file

@ -30,9 +30,12 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -35,12 +35,20 @@ namespace Jellyfin.Data.Entities
/// <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>();

View file

@ -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();
} }

View file

@ -30,10 +30,18 @@ namespace Jellyfin.Data.Entities
/// <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>();

View file

@ -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();
} }

View file

@ -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();
} }

View file

@ -35,13 +35,25 @@ namespace Jellyfin.Data.Entities
/// <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>();

View file

@ -35,13 +35,25 @@ namespace Jellyfin.Data.Entities
/// <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>();

View file

@ -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>();

View file

@ -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>();

View file

@ -31,15 +31,26 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -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();
} }

View file

@ -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();
} }

View file

@ -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();
} }

View file

@ -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>();

View file

@ -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>();

View file

@ -32,15 +32,26 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -35,13 +35,25 @@ namespace Jellyfin.Data.Entities
/// <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>();

View file

@ -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>();

View file

@ -31,15 +31,26 @@ namespace Jellyfin.Data.Entities
/// <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();
} }

View file

@ -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)
{ {

View file

@ -252,7 +252,11 @@ 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);
} }

View file

@ -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);
} }

View file

@ -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>();

View file

@ -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)
{ {

View file

@ -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);
} }

View file

@ -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)))
{ {

View file

@ -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);

View file

@ -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);

View file

@ -22,7 +22,10 @@ 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;

View file

@ -16,7 +16,10 @@ 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;
} }

View file

@ -19,7 +19,10 @@ 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;

View file

@ -23,7 +23,10 @@ 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);
}
} }
/// <summary> /// <summary>

View file

@ -31,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>()))
{ {
@ -66,10 +77,16 @@ 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));
} }

View file

@ -45,11 +45,21 @@ 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;

View file

@ -57,11 +57,21 @@ 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());

View file

@ -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(

View file

@ -80,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();
@ -151,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();
@ -234,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);

View file

@ -259,9 +259,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)
@ -287,7 +298,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)

View file

@ -27,7 +27,10 @@ namespace Rssdp.Infrastructure
/// </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;
@ -140,10 +143,25 @@ 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();
@ -192,7 +210,10 @@ 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)
@ -210,11 +231,16 @@ 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));
}
} }
/// <summary> /// <summary>
@ -281,7 +307,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);
} }
@ -318,7 +347,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)
@ -339,13 +371,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)
@ -454,14 +493,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);
} }
private void RemoveExpiredDevicesFromCache() private void RemoveExpiredDevicesFromCache()
{ {
if (this.IsDisposed) return; if (this.IsDisposed)
{
return;
}
DiscoveredSsdpDevice[] expiredDevices = null; DiscoveredSsdpDevice[] expiredDevices = null;
lock (_Devices) lock (_Devices)
@ -470,7 +515,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);
} }
@ -481,7 +529,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);
} }
@ -495,7 +546,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);
} }

View file

@ -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)
@ -227,10 +256,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 +274,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)
@ -382,7 +424,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 +439,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);
} }
@ -547,7 +595,10 @@ namespace Rssdp.Infrastructure
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))
{ {