Merge branch 'master' into feature/ffmpeg-version-check

This commit is contained in:
Max Git 2020-06-23 09:20:50 +02:00
commit c35c401d65
276 changed files with 2239 additions and 961 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

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

View File

@ -35,8 +35,6 @@ namespace Emby.Dlna.Main
private readonly IServerConfigurationManager _config; private readonly IServerConfigurationManager _config;
private readonly ILogger<DlnaEntryPoint> _logger; private readonly ILogger<DlnaEntryPoint> _logger;
private readonly IServerApplicationHost _appHost; private readonly IServerApplicationHost _appHost;
private PlayToManager _manager;
private readonly ISessionManager _sessionManager; private readonly ISessionManager _sessionManager;
private readonly IHttpClient _httpClient; private readonly IHttpClient _httpClient;
private readonly ILibraryManager _libraryManager; private readonly ILibraryManager _libraryManager;
@ -47,14 +45,13 @@ namespace Emby.Dlna.Main
private readonly ILocalizationManager _localization; private readonly ILocalizationManager _localization;
private readonly IMediaSourceManager _mediaSourceManager; private readonly IMediaSourceManager _mediaSourceManager;
private readonly IMediaEncoder _mediaEncoder; private readonly IMediaEncoder _mediaEncoder;
private readonly IDeviceDiscovery _deviceDiscovery; private readonly IDeviceDiscovery _deviceDiscovery;
private SsdpDevicePublisher _Publisher;
private readonly ISocketFactory _socketFactory; private readonly ISocketFactory _socketFactory;
private readonly INetworkManager _networkManager; private readonly INetworkManager _networkManager;
private readonly object _syncLock = new object();
private PlayToManager _manager;
private SsdpDevicePublisher _publisher;
private ISsdpCommunicationsServer _communicationsServer; private ISsdpCommunicationsServer _communicationsServer;
internal IContentDirectory ContentDirectory { get; private set; } internal IContentDirectory ContentDirectory { get; private set; }
@ -181,7 +178,7 @@ namespace Emby.Dlna.Main
var enableMultiSocketBinding = OperatingSystem.Id == OperatingSystemId.Windows || var enableMultiSocketBinding = OperatingSystem.Id == OperatingSystemId.Windows ||
OperatingSystem.Id == OperatingSystemId.Linux; OperatingSystem.Id == OperatingSystemId.Linux;
_communicationsServer = new SsdpCommunicationsServer(_config, _socketFactory, _networkManager, _logger, enableMultiSocketBinding) _communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding)
{ {
IsShared = true IsShared = true
}; };
@ -232,20 +229,22 @@ namespace Emby.Dlna.Main
return; return;
} }
if (_Publisher != null) if (_publisher != null)
{ {
return; return;
} }
try try
{ {
_Publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost); _publisher = new SsdpDevicePublisher(_communicationsServer, _networkManager, OperatingSystem.Name, Environment.OSVersion.VersionString, _config.GetDlnaConfiguration().SendOnlyMatchedHost)
_Publisher.LogFunction = LogMessage; {
_Publisher.SupportPnpRootDevice = false; LogFunction = LogMessage,
SupportPnpRootDevice = false
};
await RegisterServerEndpoints().ConfigureAwait(false); await RegisterServerEndpoints().ConfigureAwait(false);
_Publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds)); _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -267,6 +266,12 @@ namespace Emby.Dlna.Main
continue; continue;
} }
// Limit to LAN addresses only
if (!_networkManager.IsAddressInSubnets(address, true, true))
{
continue;
}
var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
_logger.LogInformation("Registering publisher for {0} on {1}", fullService, address); _logger.LogInformation("Registering publisher for {0} on {1}", fullService, address);
@ -288,13 +293,13 @@ namespace Emby.Dlna.Main
}; };
SetProperies(device, fullService); SetProperies(device, fullService);
_Publisher.AddDevice(device); _publisher.AddDevice(device);
var embeddedDevices = new[] var embeddedDevices = new[]
{ {
"urn:schemas-upnp-org:service:ContentDirectory:1", "urn:schemas-upnp-org:service:ContentDirectory:1",
"urn:schemas-upnp-org:service:ConnectionManager:1", "urn:schemas-upnp-org:service:ConnectionManager:1",
//"urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1" // "urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1"
}; };
foreach (var subDevice in embeddedDevices) foreach (var subDevice in embeddedDevices)
@ -326,7 +331,7 @@ namespace Emby.Dlna.Main
private void SetProperies(SsdpDevice device, string fullDeviceType) private void SetProperies(SsdpDevice device, string fullDeviceType)
{ {
var service = fullDeviceType.Replace("urn:", string.Empty).Replace(":1", string.Empty); var service = fullDeviceType.Replace("urn:", string.Empty, StringComparison.OrdinalIgnoreCase).Replace(":1", string.Empty, StringComparison.OrdinalIgnoreCase);
var serviceParts = service.Split(':'); var serviceParts = service.Split(':');
@ -337,7 +342,6 @@ namespace Emby.Dlna.Main
device.DeviceType = serviceParts[2]; device.DeviceType = serviceParts[2];
} }
private readonly object _syncLock = new object();
private void StartPlayToManager() private void StartPlayToManager()
{ {
lock (_syncLock) lock (_syncLock)
@ -416,11 +420,11 @@ namespace Emby.Dlna.Main
public void DisposeDevicePublisher() public void DisposeDevicePublisher()
{ {
if (_Publisher != null) if (_publisher != null)
{ {
_logger.LogInformation("Disposing SsdpDevicePublisher"); _logger.LogInformation("Disposing SsdpDevicePublisher");
_Publisher.Dispose(); _publisher.Dispose();
_Publisher = null; _publisher = null;
} }
} }
} }

View File

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

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

@ -1234,7 +1234,7 @@ namespace Emby.Server.Implementations
if (addresses.Count == 0) if (addresses.Count == 0)
{ {
addresses.AddRange(_networkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces)); addresses.AddRange(_networkManager.GetLocalIpAddresses());
} }
var resultList = new List<IPAddress>(); var resultList = new List<IPAddress>();

View File

@ -17,7 +17,6 @@ namespace Emby.Server.Implementations
{ {
{ HostWebClientKey, bool.TrueString }, { HostWebClientKey, bool.TrueString },
{ HttpListenerHost.DefaultRedirectKey, "web/index.html" }, { HttpListenerHost.DefaultRedirectKey, "web/index.html" },
{ InstallationManager.PluginManifestUrlKey, "https://repo.jellyfin.org/releases/plugin/manifest-stable.json" },
{ FfmpegProbeSizeKey, "1G" }, { FfmpegProbeSizeKey, "1G" },
{ FfmpegAnalyzeDurationKey, "200M" }, { FfmpegAnalyzeDurationKey, "200M" },
{ PlaylistsAllowDuplicatesKey, bool.TrueString } { PlaylistsAllowDuplicatesKey, bool.TrueString }

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

View File

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

View File

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

View File

@ -51,6 +51,22 @@ namespace Emby.Server.Implementations.HttpServer.Security
return user; return user;
} }
public AuthorizationInfo Authenticate(HttpRequest request)
{
var auth = _authorizationContext.GetAuthorizationInfo(request);
if (auth?.User == null)
{
return null;
}
if (auth.User.HasPermission(PermissionKind.IsDisabled))
{
throw new SecurityException("User account has been disabled.");
}
return auth;
}
private User ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues) private User ValidateUser(IRequest request, IAuthenticationAttributes authAttribtues)
{ {
// This code is executed before the service // This code is executed before the service

View File

@ -8,6 +8,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security; using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Services; using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer.Security namespace Emby.Server.Implementations.HttpServer.Security
@ -38,6 +39,14 @@ namespace Emby.Server.Implementations.HttpServer.Security
return GetAuthorization(requestContext); return GetAuthorization(requestContext);
} }
public AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext)
{
var auth = GetAuthorizationDictionary(requestContext);
var (authInfo, _) =
GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query);
return authInfo;
}
/// <summary> /// <summary>
/// Gets the authorization. /// Gets the authorization.
/// </summary> /// </summary>
@ -46,7 +55,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
private AuthorizationInfo GetAuthorization(IRequest httpReq) private AuthorizationInfo GetAuthorization(IRequest httpReq)
{ {
var auth = GetAuthorizationDictionary(httpReq); var auth = GetAuthorizationDictionary(httpReq);
var (authInfo, originalAuthInfo) =
GetAuthorizationInfoFromDictionary(auth, httpReq.Headers, httpReq.QueryString);
if (originalAuthInfo != null)
{
httpReq.Items["OriginalAuthenticationInfo"] = originalAuthInfo;
}
httpReq.Items["AuthorizationInfo"] = authInfo;
return authInfo;
}
private (AuthorizationInfo authInfo, AuthenticationInfo originalAuthenticationInfo) GetAuthorizationInfoFromDictionary(
in Dictionary<string, string> auth,
in IHeaderDictionary headers,
in IQueryCollection queryString)
{
string deviceId = null; string deviceId = null;
string device = null; string device = null;
string client = null; string client = null;
@ -64,20 +89,20 @@ namespace Emby.Server.Implementations.HttpServer.Security
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
token = httpReq.Headers["X-Emby-Token"]; token = headers["X-Emby-Token"];
} }
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
token = httpReq.Headers["X-MediaBrowser-Token"]; token = headers["X-MediaBrowser-Token"];
} }
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{ {
token = httpReq.QueryString["api_key"]; token = queryString["api_key"];
} }
var info = new AuthorizationInfo var authInfo = new AuthorizationInfo
{ {
Client = client, Client = client,
Device = device, Device = device,
@ -86,6 +111,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
Token = token Token = token
}; };
AuthenticationInfo originalAuthenticationInfo = null;
if (!string.IsNullOrWhiteSpace(token)) if (!string.IsNullOrWhiteSpace(token))
{ {
var result = _authRepo.Get(new AuthenticationInfoQuery var result = _authRepo.Get(new AuthenticationInfoQuery
@ -93,81 +119,77 @@ namespace Emby.Server.Implementations.HttpServer.Security
AccessToken = token AccessToken = token
}); });
var tokenInfo = result.Items.Count > 0 ? result.Items[0] : null; originalAuthenticationInfo = result.Items.Count > 0 ? result.Items[0] : null;
if (tokenInfo != null) if (originalAuthenticationInfo != null)
{ {
var updateToken = false; var updateToken = false;
// TODO: Remove these checks for IsNullOrWhiteSpace // TODO: Remove these checks for IsNullOrWhiteSpace
if (string.IsNullOrWhiteSpace(info.Client)) if (string.IsNullOrWhiteSpace(authInfo.Client))
{ {
info.Client = tokenInfo.AppName; authInfo.Client = originalAuthenticationInfo.AppName;
} }
if (string.IsNullOrWhiteSpace(info.DeviceId)) if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
{ {
info.DeviceId = tokenInfo.DeviceId; authInfo.DeviceId = originalAuthenticationInfo.DeviceId;
} }
// Temporary. TODO - allow clients to specify that the token has been shared with a casting device // Temporary. TODO - allow clients to specify that the token has been shared with a casting device
var allowTokenInfoUpdate = info.Client == null || info.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1; var allowTokenInfoUpdate = authInfo.Client == null || authInfo.Client.IndexOf("chromecast", StringComparison.OrdinalIgnoreCase) == -1;
if (string.IsNullOrWhiteSpace(info.Device)) if (string.IsNullOrWhiteSpace(authInfo.Device))
{ {
info.Device = tokenInfo.DeviceName; authInfo.Device = originalAuthenticationInfo.DeviceName;
} }
else if (!string.Equals(info.Device, tokenInfo.DeviceName, StringComparison.OrdinalIgnoreCase)) else if (!string.Equals(authInfo.Device, originalAuthenticationInfo.DeviceName, StringComparison.OrdinalIgnoreCase))
{ {
if (allowTokenInfoUpdate) if (allowTokenInfoUpdate)
{ {
updateToken = true; updateToken = true;
tokenInfo.DeviceName = info.Device; originalAuthenticationInfo.DeviceName = authInfo.Device;
} }
} }
if (string.IsNullOrWhiteSpace(info.Version)) if (string.IsNullOrWhiteSpace(authInfo.Version))
{ {
info.Version = tokenInfo.AppVersion; authInfo.Version = originalAuthenticationInfo.AppVersion;
} }
else if (!string.Equals(info.Version, tokenInfo.AppVersion, StringComparison.OrdinalIgnoreCase)) else if (!string.Equals(authInfo.Version, originalAuthenticationInfo.AppVersion, StringComparison.OrdinalIgnoreCase))
{ {
if (allowTokenInfoUpdate) if (allowTokenInfoUpdate)
{ {
updateToken = true; updateToken = true;
tokenInfo.AppVersion = info.Version; originalAuthenticationInfo.AppVersion = authInfo.Version;
} }
} }
if ((DateTime.UtcNow - tokenInfo.DateLastActivity).TotalMinutes > 3) if ((DateTime.UtcNow - originalAuthenticationInfo.DateLastActivity).TotalMinutes > 3)
{ {
tokenInfo.DateLastActivity = DateTime.UtcNow; originalAuthenticationInfo.DateLastActivity = DateTime.UtcNow;
updateToken = true; updateToken = true;
} }
if (!tokenInfo.UserId.Equals(Guid.Empty)) if (!originalAuthenticationInfo.UserId.Equals(Guid.Empty))
{ {
info.User = _userManager.GetUserById(tokenInfo.UserId); authInfo.User = _userManager.GetUserById(originalAuthenticationInfo.UserId);
if (info.User != null && !string.Equals(info.User.Username, tokenInfo.UserName, StringComparison.OrdinalIgnoreCase)) if (authInfo.User != null && !string.Equals(authInfo.User.Username, originalAuthenticationInfo.UserName, StringComparison.OrdinalIgnoreCase))
{ {
tokenInfo.UserName = info.User.Username; originalAuthenticationInfo.UserName = authInfo.User.Username;
updateToken = true; updateToken = true;
} }
} }
if (updateToken) if (updateToken)
{ {
_authRepo.Update(tokenInfo); _authRepo.Update(originalAuthenticationInfo);
} }
} }
httpReq.Items["OriginalAuthenticationInfo"] = tokenInfo;
} }
httpReq.Items["AuthorizationInfo"] = info; return (authInfo, originalAuthenticationInfo);
return info;
} }
/// <summary> /// <summary>
@ -187,6 +209,23 @@ namespace Emby.Server.Implementations.HttpServer.Security
return GetAuthorization(auth); return GetAuthorization(auth);
} }
/// <summary>
/// Gets the auth.
/// </summary>
/// <param name="httpReq">The HTTP req.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
private Dictionary<string, string> GetAuthorizationDictionary(HttpRequest httpReq)
{
var auth = httpReq.Headers["X-Emby-Authorization"];
if (string.IsNullOrEmpty(auth))
{
auth = httpReq.Headers[HeaderNames.Authorization];
}
return GetAuthorization(auth);
}
/// <summary> /// <summary>
/// Gets the authorization. /// Gets the authorization.
/// </summary> /// </summary>

View File

@ -36,11 +36,6 @@ namespace Emby.Server.Implementations
/// </summary> /// </summary>
string RestartArgs { get; } string RestartArgs { get; }
/// <summary>
/// Gets the value of the --plugin-manifest-url command line option.
/// </summary>
string PluginManifestUrl { get; }
/// <summary> /// <summary>
/// Gets the value of the --published-server-url command line option. /// Gets the value of the --published-server-url command line option.
/// </summary> /// </summary>

View File

@ -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)
{ {
@ -2897,7 +2897,8 @@ namespace Emby.Server.Implementations.Library
} }
catch (HttpException ex) catch (HttpException ex)
{ {
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound) if (ex.StatusCode.HasValue
&& (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
{ {
continue; continue;
} }

View File

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

View File

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

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

View File

@ -1,5 +1,5 @@
{ {
"LabelRunningTimeValue": "Duración: {0}", "LabelRunningTimeValue": "Tiempo en ejecución: {0}",
"ValueSpecialEpisodeName": "Especial - {0}", "ValueSpecialEpisodeName": "Especial - {0}",
"Sync": "Sincronizar", "Sync": "Sincronizar",
"Songs": "Canciones", "Songs": "Canciones",

View File

@ -0,0 +1,62 @@
{
"NotificationOptionUserLockedOut": "प्रयोगकर्ता प्रतिबन्धित",
"NotificationOptionTaskFailed": "निर्धारित कार्य विफलता",
"NotificationOptionServerRestartRequired": "सर्भर रिस्टार्ट आवाश्यक छ",
"NotificationOptionPluginUpdateInstalled": "प्लगइन अद्यावधिक स्थापना भयो",
"NotificationOptionPluginUninstalled": "प्लगइन विस्थापित",
"NotificationOptionPluginInstalled": "प्लगइन स्थापना भयो",
"NotificationOptionPluginError": "प्लगइन असफलता",
"NotificationOptionNewLibraryContent": "नयाँ सामग्री थपियो",
"NotificationOptionInstallationFailed": "स्थापना असफलता",
"NotificationOptionCameraImageUploaded": "क्यामेरा फोटो अपलोड गरियो",
"NotificationOptionAudioPlaybackStopped": "ध्वनि प्रक्षेपण रोकियो",
"NotificationOptionAudioPlayback": "ध्वनि प्रक्षेपण शुरू भयो",
"NotificationOptionApplicationUpdateInstalled": "अनुप्रयोग अद्यावधिक स्थापना भयो",
"NotificationOptionApplicationUpdateAvailable": "अनुप्रयोग अपडेट उपलब्ध छ",
"NewVersionIsAvailable": "जेलीफिन सर्भर को नयाँ संस्करण डाउनलोड को लागी उपलब्ध छ।",
"NameSeasonUnknown": "अज्ञात श्रृंखला",
"NameSeasonNumber": "श्रृंखला {0}",
"NameInstallFailed": "{0} स्थापना असफल भयो",
"MusicVideos": "सांगीतिक भिडियोहरू",
"Music": "संगीत",
"Movies": "चलचित्रहरू",
"MixedContent": "मिश्रित सामग्री",
"MessageServerConfigurationUpdated": "सर्भर कन्फिगरेसन अद्यावधिक गरिएको छ",
"MessageNamedServerConfigurationUpdatedWithValue": "सर्भर कन्फिगरेसन विभाग {0} अद्यावधिक गरिएको छ",
"MessageApplicationUpdatedTo": "जेलीफिन सर्भर {0} मा अद्यावधिक गरिएको छ",
"MessageApplicationUpdated": "जेलीफिन सर्भर अपडेट गरिएको छ",
"Latest": "नविनतम",
"LabelRunningTimeValue": "कुल समय: {0}",
"LabelIpAddressValue": "आईपी ठेगाना: {0}",
"ItemRemovedWithName": "{0}लाई पुस्तकालयबाट हटाईयो",
"ItemAddedWithName": "{0} लाईब्रेरीमा थपियो",
"Inherit": "इनहेरिट",
"HomeVideos": "घरेलु भिडियोहरू",
"HeaderRecordingGroups": "रेकर्ड समूहहरू",
"HeaderNextUp": "आगामी",
"HeaderLiveTV": "प्रत्यक्ष टिभी",
"HeaderFavoriteSongs": "मनपर्ने गीतहरू",
"HeaderFavoriteShows": "मनपर्ने कार्यक्रमहरू",
"HeaderFavoriteEpisodes": "मनपर्ने एपिसोडहरू",
"HeaderFavoriteArtists": "मनपर्ने कलाकारहरू",
"HeaderFavoriteAlbums": "मनपर्ने एल्बमहरू",
"HeaderContinueWatching": "हेर्न जारी राख्नुहोस्",
"HeaderCameraUploads": "क्यामेरा अपलोडहरू",
"HeaderAlbumArtists": "एल्बमका कलाकारहरू",
"Genres": "विधाहरू",
"Folders": "फोल्डरहरू",
"Favorites": "मनपर्ने",
"FailedLoginAttemptWithUserName": "{0}को लग इन प्रयास असफल",
"DeviceOnlineWithName": "{0}को साथ जडित",
"DeviceOfflineWithName": "{0}बाट विच्छेदन भयो",
"Collections": "संग्रह",
"ChapterNameValue": "अध्याय {0}",
"Channels": "च्यानलहरू",
"AppDeviceValues": "अनुप्रयोग: {0}, उपकरण: {1}",
"AuthenticationSucceededWithUserName": "{0} सफलतापूर्वक प्रमाणीकरण गरियो",
"CameraImageUploadedFrom": "{0}बाट नयाँ क्यामेरा छवि अपलोड गरिएको छ",
"Books": "पुस्तकहरु",
"Artists": "कलाकारहरू",
"Application": "अनुप्रयोगहरू",
"Albums": "एल्बमहरू"
}

View File

@ -1,6 +1,6 @@
{ {
"Albums": "專輯", "Albums": "專輯",
"AppDeviceValues": "軟件: {0}, 設備: {1}", "AppDeviceValues": "程式: {0}, 設備: {1}",
"Application": "應用程式", "Application": "應用程式",
"Artists": "藝人", "Artists": "藝人",
"AuthenticationSucceededWithUserName": "{0} 授權成功", "AuthenticationSucceededWithUserName": "{0} 授權成功",
@ -113,5 +113,6 @@
"TaskCleanCacheDescription": "刪除系統不再需要的緩存文件。", "TaskCleanCacheDescription": "刪除系統不再需要的緩存文件。",
"TaskCleanCache": "清理緩存目錄", "TaskCleanCache": "清理緩存目錄",
"TasksChannelsCategory": "互聯網頻道", "TasksChannelsCategory": "互聯網頻道",
"TasksLibraryCategory": "庫" "TasksLibraryCategory": "庫",
"TaskRefreshPeople": "刷新人物"
} }

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

@ -2,7 +2,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
@ -13,6 +12,9 @@ using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Networking namespace Emby.Server.Implementations.Networking
{ {
/// <summary>
/// Class to take care of network interface management.
/// </summary>
public class NetworkManager : INetworkManager public class NetworkManager : INetworkManager
{ {
private readonly ILogger<NetworkManager> _logger; private readonly ILogger<NetworkManager> _logger;
@ -21,8 +23,14 @@ namespace Emby.Server.Implementations.Networking
private readonly object _localIpAddressSyncLock = new object(); private readonly object _localIpAddressSyncLock = new object();
private readonly object _subnetLookupLock = new object(); private readonly object _subnetLookupLock = new object();
private Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal); private readonly Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
private List<PhysicalAddress> _macAddresses;
/// <summary>
/// Initializes a new instance of the <see cref="NetworkManager"/> class.
/// </summary>
/// <param name="logger">Logger to use for messages.</param>
public NetworkManager(ILogger<NetworkManager> logger) public NetworkManager(ILogger<NetworkManager> logger)
{ {
_logger = logger; _logger = logger;
@ -31,8 +39,10 @@ namespace Emby.Server.Implementations.Networking
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
} }
/// <inheritdoc/>
public event EventHandler NetworkChanged; public event EventHandler NetworkChanged;
/// <inheritdoc/>
public Func<string[]> LocalSubnetsFn { get; set; } public Func<string[]> LocalSubnetsFn { get; set; }
private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
@ -58,13 +68,14 @@ namespace Emby.Server.Implementations.Networking
NetworkChanged?.Invoke(this, EventArgs.Empty); NetworkChanged?.Invoke(this, EventArgs.Empty);
} }
public IPAddress[] GetLocalIpAddresses(bool ignoreVirtualInterface = true) /// <inheritdoc/>
public IPAddress[] GetLocalIpAddresses()
{ {
lock (_localIpAddressSyncLock) lock (_localIpAddressSyncLock)
{ {
if (_localIpAddresses == null) if (_localIpAddresses == null)
{ {
var addresses = GetLocalIpAddressesInternal(ignoreVirtualInterface).ToArray(); var addresses = GetLocalIpAddressesInternal().ToArray();
_localIpAddresses = addresses; _localIpAddresses = addresses;
} }
@ -73,42 +84,47 @@ namespace Emby.Server.Implementations.Networking
} }
} }
private List<IPAddress> GetLocalIpAddressesInternal(bool ignoreVirtualInterface) private List<IPAddress> GetLocalIpAddressesInternal()
{ {
var list = GetIPsDefault(ignoreVirtualInterface).ToList(); var list = GetIPsDefault().ToList();
if (list.Count == 0) if (list.Count == 0)
{ {
list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList(); list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList();
} }
var listClone = list.ToList(); var listClone = new List<IPAddress>();
return list var subnets = LocalSubnetsFn();
foreach (var i in list)
{
if (i.IsIPv6LinkLocal || i.ToString().StartsWith("169.254.", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (Array.IndexOf(subnets, $"[{i}]") == -1)
{
listClone.Add(i);
}
}
return listClone
.OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1) .OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1)
.ThenBy(i => listClone.IndexOf(i)) // .ThenBy(i => listClone.IndexOf(i))
.Where(FilterIpAddress)
.GroupBy(i => i.ToString()) .GroupBy(i => i.ToString())
.Select(x => x.First()) .Select(x => x.First())
.ToList(); .ToList();
} }
private static bool FilterIpAddress(IPAddress address) /// <inheritdoc/>
{
if (address.IsIPv6LinkLocal
|| address.ToString().StartsWith("169.", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
public bool IsInPrivateAddressSpace(string endpoint) public bool IsInPrivateAddressSpace(string endpoint)
{ {
return IsInPrivateAddressSpace(endpoint, true); return IsInPrivateAddressSpace(endpoint, true);
} }
// Checks if the address in endpoint is an RFC1918, RFC1122, or RFC3927 address
private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets) private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets)
{ {
if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
@ -116,12 +132,12 @@ namespace Emby.Server.Implementations.Networking
return true; return true;
} }
// ipv6 // IPV6
if (endpoint.Split('.').Length > 4) if (endpoint.Split('.').Length > 4)
{ {
// Handle ipv4 mapped to ipv6 // Handle ipv4 mapped to ipv6
var originalEndpoint = endpoint; var originalEndpoint = endpoint;
endpoint = endpoint.Replace("::ffff:", string.Empty); endpoint = endpoint.Replace("::ffff:", string.Empty, StringComparison.OrdinalIgnoreCase);
if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
{ {
@ -130,23 +146,21 @@ namespace Emby.Server.Implementations.Networking
} }
// Private address space: // Private address space:
// http://en.wikipedia.org/wiki/Private_network
if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "localhost", StringComparison.OrdinalIgnoreCase))
{
return Is172AddressPrivate(endpoint);
}
if (endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
{ {
return true; return true;
} }
if (checkSubnets && endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase)) byte[] octet = IPAddress.Parse(endpoint).GetAddressBytes();
if ((octet[0] == 10) ||
(octet[0] == 172 && (octet[1] >= 16 && octet[1] <= 31)) || // RFC1918
(octet[0] == 192 && octet[1] == 168) || // RFC1918
(octet[0] == 127) || // RFC1122
(octet[0] == 169 && octet[1] == 254)) // RFC3927
{ {
return true; return false;
} }
if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint)) if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint))
@ -157,6 +171,7 @@ namespace Emby.Server.Implementations.Networking
return false; return false;
} }
/// <inheritdoc/>
public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint) public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
{ {
if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase)) if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase))
@ -179,6 +194,7 @@ namespace Emby.Server.Implementations.Networking
return false; return false;
} }
// Gives a list of possible subnets from the system whose interface ip starts with endpointFirstPart
private List<string> GetSubnets(string endpointFirstPart) private List<string> GetSubnets(string endpointFirstPart)
{ {
lock (_subnetLookupLock) lock (_subnetLookupLock)
@ -224,46 +240,75 @@ namespace Emby.Server.Implementations.Networking
} }
} }
private static bool Is172AddressPrivate(string endpoint) /// <inheritdoc/>
{
for (var i = 16; i <= 31; i++)
{
if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
public bool IsInLocalNetwork(string endpoint) public bool IsInLocalNetwork(string endpoint)
{ {
return IsInLocalNetworkInternal(endpoint, true); return IsInLocalNetworkInternal(endpoint, true);
} }
/// <inheritdoc/>
public bool IsAddressInSubnets(string addressString, string[] subnets) public bool IsAddressInSubnets(string addressString, string[] subnets)
{ {
return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets); return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets);
} }
/// <inheritdoc/>
public bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC)
{
byte[] octet = address.GetAddressBytes();
if ((octet[0] == 127) || // RFC1122
(octet[0] == 169 && octet[1] == 254)) // RFC3927
{
// don't use on loopback or 169 interfaces
return false;
}
string addressString = address.ToString();
string excludeAddress = "[" + addressString + "]";
var subnets = LocalSubnetsFn();
// Exclude any addresses if they appear in the LAN list in [ ]
if (Array.IndexOf(subnets, excludeAddress) != -1)
{
return false;
}
return IsAddressInSubnets(address, addressString, subnets);
}
/// <summary>
/// Checks if the give address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
/// </summary>
/// <param name="address">IPAddress version of the address.</param>
/// <param name="addressString">The address to check.</param>
/// <param name="subnets">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
/// <returns><c>false</c>if the address isn't in the subnets, <c>true</c> otherwise.</returns>
private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets) private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets)
{ {
foreach (var subnet in subnets) foreach (var subnet in subnets)
{ {
var normalizedSubnet = subnet.Trim(); var normalizedSubnet = subnet.Trim();
// Is the subnet a host address and does it match the address being passes?
if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase)) if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase))
{ {
return true; return true;
} }
// Parse CIDR subnets and see if address falls within it.
if (normalizedSubnet.Contains('/', StringComparison.Ordinal)) if (normalizedSubnet.Contains('/', StringComparison.Ordinal))
{ {
var ipNetwork = IPNetwork.Parse(normalizedSubnet); try
if (ipNetwork.Contains(address))
{ {
return true; var ipNetwork = IPNetwork.Parse(normalizedSubnet);
if (ipNetwork.Contains(address))
{
return true;
}
}
catch
{
// Ignoring - invalid subnet passed encountered.
} }
} }
} }
@ -288,7 +333,7 @@ namespace Emby.Server.Implementations.Networking
var localSubnets = localSubnetsFn(); var localSubnets = localSubnetsFn();
foreach (var subnet in localSubnets) foreach (var subnet in localSubnets)
{ {
// only validate if there's at least one valid entry // Only validate if there's at least one valid entry.
if (!string.IsNullOrWhiteSpace(subnet)) if (!string.IsNullOrWhiteSpace(subnet))
{ {
return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false); return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false);
@ -345,7 +390,7 @@ namespace Emby.Server.Implementations.Networking
} }
catch (InvalidOperationException) catch (InvalidOperationException)
{ {
// Can happen with reverse proxy or IIS url rewriting // Can happen with reverse proxy or IIS url rewriting?
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -362,7 +407,7 @@ namespace Emby.Server.Implementations.Networking
return Dns.GetHostAddressesAsync(hostName); return Dns.GetHostAddressesAsync(hostName);
} }
private IEnumerable<IPAddress> GetIPsDefault(bool ignoreVirtualInterface) private IEnumerable<IPAddress> GetIPsDefault()
{ {
IEnumerable<NetworkInterface> interfaces; IEnumerable<NetworkInterface> interfaces;
@ -382,15 +427,7 @@ namespace Emby.Server.Implementations.Networking
{ {
var ipProperties = network.GetIPProperties(); var ipProperties = network.GetIPProperties();
// Try to exclude virtual adapters // Exclude any addresses if they appear in the LAN list in [ ]
// http://stackoverflow.com/questions/8089685/c-sharp-finding-my-machines-local-ip-address-and-not-the-vms
var addr = ipProperties.GatewayAddresses.FirstOrDefault();
if (addr == null
|| (ignoreVirtualInterface
&& (addr.Address.Equals(IPAddress.Any) || addr.Address.Equals(IPAddress.IPv6Any))))
{
return Enumerable.Empty<IPAddress>();
}
return ipProperties.UnicastAddresses return ipProperties.UnicastAddresses
.Select(i => i.Address) .Select(i => i.Address)
@ -423,33 +460,29 @@ namespace Emby.Server.Implementations.Networking
return port; return port;
} }
/// <inheritdoc/>
public int GetRandomUnusedUdpPort() public int GetRandomUnusedUdpPort()
{ {
var localEndPoint = new IPEndPoint(IPAddress.Any, 0); var localEndPoint = new IPEndPoint(IPAddress.Any, 0);
using (var udpClient = new UdpClient(localEndPoint)) using (var udpClient = new UdpClient(localEndPoint))
{ {
var port = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
return port;
} }
} }
private List<PhysicalAddress> _macAddresses; /// <inheritdoc/>
public List<PhysicalAddress> GetMacAddresses() public List<PhysicalAddress> GetMacAddresses()
{ {
if (_macAddresses == null) return _macAddresses ??= GetMacAddressesInternal().ToList();
{
_macAddresses = GetMacAddressesInternal().ToList();
}
return _macAddresses;
} }
private static IEnumerable<PhysicalAddress> GetMacAddressesInternal() private static IEnumerable<PhysicalAddress> GetMacAddressesInternal()
=> NetworkInterface.GetAllNetworkInterfaces() => NetworkInterface.GetAllNetworkInterfaces()
.Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback) .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(x => x.GetPhysicalAddress()) .Select(x => x.GetPhysicalAddress())
.Where(x => x != null && x != PhysicalAddress.None); .Where(x => !x.Equals(PhysicalAddress.None));
/// <inheritdoc/>
public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask) public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask)
{ {
IPAddress network1 = GetNetworkAddress(address1, subnetMask); IPAddress network1 = GetNetworkAddress(address1, subnetMask);
@ -476,6 +509,7 @@ namespace Emby.Server.Implementations.Networking
return new IPAddress(broadcastAddress); return new IPAddress(broadcastAddress);
} }
/// <inheritdoc/>
public IPAddress GetLocalIpSubnetMask(IPAddress address) public IPAddress GetLocalIpSubnetMask(IPAddress address)
{ {
NetworkInterface[] interfaces; NetworkInterface[] interfaces;
@ -496,14 +530,11 @@ namespace Emby.Server.Implementations.Networking
foreach (NetworkInterface ni in interfaces) foreach (NetworkInterface ni in interfaces)
{ {
if (ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null) foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{ {
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) if (ip.Address.Equals(address) && ip.IPv4Mask != null)
{ {
if (ip.Address.Equals(address) && ip.IPv4Mask != null) return ip.IPv4Mask;
{
return ip.IPv4Mask;
}
} }
} }
} }

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

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

View File

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

View File

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

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

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

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

View File

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

View File

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

View File

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

View File

@ -101,11 +101,18 @@ namespace Emby.Server.Implementations.Udp
{ {
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
var infiniteTask = Task.Delay(-1, cancellationToken);
try try
{ {
var result = await _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint).ConfigureAwait(false); var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);
await Task.WhenAny(task, infiniteTask).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested(); if (!task.IsCompleted)
{
return;
}
var result = task.Result;
var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes); var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase)) if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))

View File

@ -19,6 +19,7 @@ using MediaBrowser.Common.Updates;
using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Events; using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO; using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Updates; using MediaBrowser.Model.Updates;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@ -31,11 +32,6 @@ namespace Emby.Server.Implementations.Updates
/// </summary> /// </summary>
public class InstallationManager : IInstallationManager public class InstallationManager : IInstallationManager
{ {
/// <summary>
/// The key for a setting that specifies a URL for the plugin repository JSON manifest.
/// </summary>
public const string PluginManifestUrlKey = "InstallationManager:PluginManifestUrl";
/// <summary> /// <summary>
/// The logger. /// The logger.
/// </summary> /// </summary>
@ -122,16 +118,14 @@ namespace Emby.Server.Implementations.Updates
public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal; public IEnumerable<InstallationInfo> CompletedInstallations => _completedInstallationsInternal;
/// <inheritdoc /> /// <inheritdoc />
public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default) public async Task<IEnumerable<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default)
{ {
var manifestUrl = _appConfig.GetValue<string>(PluginManifestUrlKey);
try try
{ {
using (var response = await _httpClient.SendAsync( using (var response = await _httpClient.SendAsync(
new HttpRequestOptions new HttpRequestOptions
{ {
Url = manifestUrl, Url = manifest,
CancellationToken = cancellationToken, CancellationToken = cancellationToken,
CacheMode = CacheMode.Unconditional, CacheMode = CacheMode.Unconditional,
CacheLength = TimeSpan.FromMinutes(3) CacheLength = TimeSpan.FromMinutes(3)
@ -145,23 +139,33 @@ namespace Emby.Server.Implementations.Updates
} }
catch (SerializationException ex) catch (SerializationException ex)
{ {
const string LogTemplate = _logger.LogError(ex, "Failed to deserialize the plugin manifest retrieved from {Manifest}", manifest);
"Failed to deserialize the plugin manifest retrieved from {PluginManifestUrl}. If you " + return Enumerable.Empty<PackageInfo>();
"have specified a custom plugin repository manifest URL with --plugin-manifest-url or " +
PluginManifestUrlKey + ", please ensure that it is correct.";
_logger.LogError(ex, LogTemplate, manifestUrl);
throw;
} }
} }
} }
catch (UriFormatException ex) catch (UriFormatException ex)
{ {
const string LogTemplate = _logger.LogError(ex, "The URL configured for the plugin repository manifest URL is not valid: {Manifest}", manifest);
"The URL configured for the plugin repository manifest URL is not valid: {PluginManifestUrl}. " + return Enumerable.Empty<PackageInfo>();
"Please check the URL configured by --plugin-manifest-url or " + PluginManifestUrlKey;
_logger.LogError(ex, LogTemplate, manifestUrl);
throw;
} }
catch (HttpException ex)
{
_logger.LogError(ex, "An error occurred while accessing the plugin manifest: {Manifest}", manifest);
return Enumerable.Empty<PackageInfo>();
}
}
/// <inheritdoc />
public async Task<IReadOnlyList<PackageInfo>> GetAvailablePackages(CancellationToken cancellationToken = default)
{
var result = new List<PackageInfo>();
foreach (RepositoryInfo repository in _config.Configuration.PluginRepositories)
{
result.AddRange(await GetPackages(repository.Url, cancellationToken).ConfigureAwait(true));
}
return result.AsReadOnly();
} }
/// <inheritdoc /> /// <inheritdoc />
@ -402,6 +406,12 @@ namespace Emby.Server.Implementations.Updates
/// <param name="plugin">The plugin.</param> /// <param name="plugin">The plugin.</param>
public void UninstallPlugin(IPlugin plugin) public void UninstallPlugin(IPlugin plugin)
{ {
if (!plugin.CanUninstall)
{
_logger.LogWarning("Attempt to delete non removable plugin {0}, ignoring request", plugin.Name);
return;
}
plugin.OnUninstalling(); plugin.OnUninstalling();
// Remove it the quick way for now // Remove it the quick way for now

View File

@ -39,21 +39,18 @@ namespace Jellyfin.Api.Auth
/// <inheritdoc /> /// <inheritdoc />
protected override Task<AuthenticateResult> HandleAuthenticateAsync() protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
var authenticatedAttribute = new AuthenticatedAttribute();
try try
{ {
var user = _authService.Authenticate(Request, authenticatedAttribute); var authorizationInfo = _authService.Authenticate(Request);
if (user == null) if (authorizationInfo == null)
{ {
return Task.FromResult(AuthenticateResult.Fail("Invalid user")); return Task.FromResult(AuthenticateResult.Fail("Invalid user"));
} }
var claims = new[] var claims = new[]
{ {
new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.Name, authorizationInfo.User.Username),
new Claim( new Claim(ClaimTypes.Role, authorizationInfo.User.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User)
ClaimTypes.Role,
value: user.HasPermission(PermissionKind.IsAdministrator) ? UserRoles.Administrator : UserRoles.User)
}; };
var identity = new ClaimsIdentity(claims, Scheme.Name); var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity); var principal = new ClaimsPrincipal(identity);

View File

@ -16,7 +16,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.5" /> <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="3.1.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.4.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

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

View File

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

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

View File

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

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

View File

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

View File

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

View File

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

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

View File

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

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

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

View File

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

View File

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

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

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

View File

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

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

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

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

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

View File

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

View File

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

View File

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

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

View File

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

View File

@ -63,25 +63,29 @@ namespace Jellyfin.Server.Implementations.Users
}); });
} }
byte[] passwordBytes = Encoding.UTF8.GetBytes(password); // Handle the case when the stored password is null, but the user tried to login with a password
if (resolvedUser.Password != null)
PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password);
if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id)
|| _cryptographyProvider.DefaultHashMethod == readyHash.Id)
{ {
byte[] calculatedHash = _cryptographyProvider.ComputeHash( byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
readyHash.Id,
passwordBytes,
readyHash.Salt.ToArray());
if (readyHash.Hash.SequenceEqual(calculatedHash)) PasswordHash readyHash = PasswordHash.Parse(resolvedUser.Password);
if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id)
|| _cryptographyProvider.DefaultHashMethod == readyHash.Id)
{ {
success = true; byte[] calculatedHash = _cryptographyProvider.ComputeHash(
readyHash.Id,
passwordBytes,
readyHash.Salt.ToArray());
if (readyHash.Hash.SequenceEqual(calculatedHash))
{
success = true;
}
}
else
{
throw new AuthenticationException($"Requested crypto method not available in provider: {readyHash.Id}");
} }
}
else
{
throw new AuthenticationException($"Requested crypto method not available in provider: {readyHash.Id}");
} }
if (!success) if (!success)

View File

@ -43,8 +43,8 @@
<PackageReference Include="CommandLineParser" Version="2.8.0" /> <PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.5" /> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.5" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.5" />
<PackageReference Include="prometheus-net" Version="3.5.0" /> <PackageReference Include="prometheus-net" Version="3.6.0" />
<PackageReference Include="prometheus-net.AspNetCore" Version="3.5.0" /> <PackageReference Include="prometheus-net.AspNetCore" Version="3.6.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" /> <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />

View File

@ -20,6 +20,7 @@ namespace Jellyfin.Server.Migrations
typeof(Routines.CreateUserLoggingConfigFile), typeof(Routines.CreateUserLoggingConfigFile),
typeof(Routines.MigrateActivityLogDb), typeof(Routines.MigrateActivityLogDb),
typeof(Routines.RemoveDuplicateExtras), typeof(Routines.RemoveDuplicateExtras),
typeof(Routines.AddDefaultPluginRepository),
typeof(Routines.MigrateUserDb) typeof(Routines.MigrateUserDb)
}; };

View File

@ -0,0 +1,42 @@
using System;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Updates;
namespace Jellyfin.Server.Migrations.Routines
{
/// <summary>
/// Migration to initialize system configuration with the default plugin repository.
/// </summary>
public class AddDefaultPluginRepository : IMigrationRoutine
{
private readonly IServerConfigurationManager _serverConfigurationManager;
private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo
{
Name = "Jellyfin Stable",
Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json"
};
/// <summary>
/// Initializes a new instance of the <see cref="AddDefaultPluginRepository"/> class.
/// </summary>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
public AddDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager)
{
_serverConfigurationManager = serverConfigurationManager;
}
/// <inheritdoc/>
public Guid Id => Guid.Parse("EB58EBEE-9514-4B9B-8225-12E1A40020DF");
/// <inheritdoc/>
public string Name => "AddDefaultPluginRepository";
/// <inheritdoc/>
public void Perform()
{
_serverConfigurationManager.Configuration.PluginRepositories.Add(_defaultRepositoryInfo);
_serverConfigurationManager.SaveConfiguration();
}
}
}

View File

@ -79,10 +79,6 @@ namespace Jellyfin.Server
[Option("restartargs", Required = false, HelpText = "Arguments for restart script.")] [Option("restartargs", Required = false, HelpText = "Arguments for restart script.")]
public string? RestartArgs { get; set; } public string? RestartArgs { get; set; }
/// <inheritdoc />
[Option("plugin-manifest-url", Required = false, HelpText = "A custom URL for the plugin repository JSON manifest")]
public string? PluginManifestUrl { get; set; }
/// <inheritdoc /> /// <inheritdoc />
[Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")] [Option("published-server-url", Required = false, HelpText = "Jellyfin Server URL to publish via auto discover process")]
public Uri? PublishedServerUrl { get; set; } public Uri? PublishedServerUrl { get; set; }
@ -95,11 +91,6 @@ namespace Jellyfin.Server
{ {
var config = new Dictionary<string, string>(); var config = new Dictionary<string, string>();
if (PluginManifestUrl != null)
{
config.Add(InstallationManager.PluginManifestUrlKey, PluginManifestUrl);
}
if (NoWebClient) if (NoWebClient)
{ {
config.Add(ConfigurationExtensions.HostWebClientKey, bool.FalseString); config.Add(ConfigurationExtensions.HostWebClientKey, bool.FalseString);

View File

@ -13,6 +13,18 @@ using Microsoft.Extensions.Logging;
namespace MediaBrowser.Api namespace MediaBrowser.Api
{ {
[Route("/Repositories", "GET", Summary = "Gets all package repositories")]
[Authenticated]
public class GetRepositories : IReturnVoid
{
}
[Route("/Repositories", "POST", Summary = "Sets the enabled and existing package repositories")]
[Authenticated]
public class SetRepositories : List<RepositoryInfo>, IReturnVoid
{
}
/// <summary> /// <summary>
/// Class GetPackage. /// Class GetPackage.
/// </summary> /// </summary>
@ -94,6 +106,7 @@ namespace MediaBrowser.Api
public class PackageService : BaseApiService public class PackageService : BaseApiService
{ {
private readonly IInstallationManager _installationManager; private readonly IInstallationManager _installationManager;
private readonly IServerConfigurationManager _serverConfigurationManager;
public PackageService( public PackageService(
ILogger<PackageService> logger, ILogger<PackageService> logger,
@ -103,6 +116,19 @@ namespace MediaBrowser.Api
: base(logger, serverConfigurationManager, httpResultFactory) : base(logger, serverConfigurationManager, httpResultFactory)
{ {
_installationManager = installationManager; _installationManager = installationManager;
_serverConfigurationManager = serverConfigurationManager;
}
public object Get(GetRepositories request)
{
var result = _serverConfigurationManager.Configuration.PluginRepositories;
return ToOptimizedResult(result);
}
public void Post(SetRepositories request)
{
_serverConfigurationManager.Configuration.PluginRepositories = request;
_serverConfigurationManager.SaveConfiguration();
} }
/// <summary> /// <summary>

View File

@ -11,14 +11,21 @@ namespace MediaBrowser.Common.Net
{ {
event EventHandler NetworkChanged; event EventHandler NetworkChanged;
/// <summary>
/// Gets or sets a function to return the list of user defined LAN addresses.
/// </summary>
Func<string[]> LocalSubnetsFn { get; set; } Func<string[]> LocalSubnetsFn { get; set; }
/// <summary> /// <summary>
/// Gets a random port number that is currently available. /// Gets a random port TCP number that is currently available.
/// </summary> /// </summary>
/// <returns>System.Int32.</returns> /// <returns>System.Int32.</returns>
int GetRandomUnusedTcpPort(); int GetRandomUnusedTcpPort();
/// <summary>
/// Gets a random port UDP number that is currently available.
/// </summary>
/// <returns>System.Int32.</returns>
int GetRandomUnusedUdpPort(); int GetRandomUnusedUdpPort();
/// <summary> /// <summary>
@ -34,6 +41,13 @@ namespace MediaBrowser.Common.Net
/// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInPrivateAddressSpace(string endpoint); bool IsInPrivateAddressSpace(string endpoint);
/// <summary>
/// Determines whether [is in private address space 10.x.x.x] [the specified endpoint] and exists in the subnets returned by GetSubnets().
/// </summary>
/// <param name="endpoint">The endpoint.</param>
/// <returns><c>true</c> if [is in private address space 10.x.x.x] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint);
/// <summary> /// <summary>
/// Determines whether [is in local network] [the specified endpoint]. /// Determines whether [is in local network] [the specified endpoint].
/// </summary> /// </summary>
@ -41,12 +55,43 @@ namespace MediaBrowser.Common.Net
/// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns> /// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns>
bool IsInLocalNetwork(string endpoint); bool IsInLocalNetwork(string endpoint);
IPAddress[] GetLocalIpAddresses(bool ignoreVirtualInterface); /// <summary>
/// Investigates an caches a list of interface addresses, excluding local link and LAN excluded addresses.
/// </summary>
/// <returns>The list of ipaddresses.</returns>
IPAddress[] GetLocalIpAddresses();
/// <summary>
/// Checks if the given address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
/// </summary>
/// <param name="addressString">The address to check.</param>
/// <param name="subnets">If true, check against addresses in the LAN settings surrounded by brackets ([]).</param>
/// <returns><c>true</c>if the address is in at least one of the given subnets, <c>false</c> otherwise.</returns>
bool IsAddressInSubnets(string addressString, string[] subnets); bool IsAddressInSubnets(string addressString, string[] subnets);
/// <summary>
/// Returns true if address is in the LAN list in the config file.
/// </summary>
/// <param name="address">The address to check.</param>
/// <param name="excludeInterfaces">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
/// <param name="excludeRFC">If true, returns false if address is in the 127.x.x.x or 169.128.x.x range.</param>
/// <returns><c>false</c>if the address isn't in the LAN list, <c>true</c> if the address has been defined as a LAN address.</returns>
bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC);
/// <summary>
/// Checks if address is in the LAN list in the config file.
/// </summary>
/// <param name="address1">Source address to check.</param>
/// <param name="address2">Destination address to check against.</param>
/// <param name="subnetMask">Destination subnet to check against.</param>
/// <returns><c>true/false</c>depending on whether address1 is in the same subnet as IPAddress2 with subnetMask.</returns>
bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask); bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask);
/// <summary>
/// Returns the subnet mask of an interface with the given address.
/// </summary>
/// <param name="address">The address to check.</param>
/// <returns>Returns the subnet mask of an interface with the given address, or null if an interface match cannot be found.</returns>
IPAddress GetLocalIpSubnetMask(IPAddress address); IPAddress GetLocalIpSubnetMask(IPAddress address);
} }
} }

View File

@ -2,6 +2,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Reflection;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Serialization;
@ -49,6 +50,12 @@ namespace MediaBrowser.Common.Plugins
/// <value>The data folder path.</value> /// <value>The data folder path.</value>
public string DataFolderPath { get; private set; } public string DataFolderPath { get; private set; }
/// <summary>
/// Gets a value indicating whether the plugin can be uninstalled.
/// </summary>
public bool CanUninstall => !Path.GetDirectoryName(AssemblyFilePath)
.Equals(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), StringComparison.InvariantCulture);
/// <summary> /// <summary>
/// Gets the plugin info. /// Gets the plugin info.
/// </summary> /// </summary>
@ -60,7 +67,8 @@ namespace MediaBrowser.Common.Plugins
Name = Name, Name = Name,
Version = Version.ToString(), Version = Version.ToString(),
Description = Description, Description = Description,
Id = Id.ToString() Id = Id.ToString(),
CanUninstall = CanUninstall
}; };
return info; return info;

View File

@ -40,6 +40,11 @@ namespace MediaBrowser.Common.Plugins
/// <value>The assembly file path.</value> /// <value>The assembly file path.</value>
string AssemblyFilePath { get; } string AssemblyFilePath { get; }
/// <summary>
/// Gets a value indicating whether the plugin can be uninstalled.
/// </summary>
bool CanUninstall { get; }
/// <summary> /// <summary>
/// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed. /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed.
/// </summary> /// </summary>

View File

@ -40,6 +40,14 @@ namespace MediaBrowser.Common.Updates
/// </summary> /// </summary>
IEnumerable<InstallationInfo> CompletedInstallations { get; } IEnumerable<InstallationInfo> CompletedInstallations { get; }
/// <summary>
/// Parses a plugin manifest at the supplied URL.
/// </summary>
/// <param name="manifest">The URL to query.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{IReadOnlyList{PackageInfo}}.</returns>
Task<IEnumerable<PackageInfo>> GetPackages(string manifest, CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// Gets all available packages. /// Gets all available packages.
/// </summary> /// </summary>

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,5 +11,12 @@ namespace MediaBrowser.Controller.Net
void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues); void Authenticate(IRequest request, IAuthenticationAttributes authAttribtues);
User? Authenticate(HttpRequest request, IAuthenticationAttributes authAttribtues); User? Authenticate(HttpRequest request, IAuthenticationAttributes authAttribtues);
/// <summary>
/// Authenticate request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Authorization information. Null if unauthenticated.</returns>
AuthorizationInfo Authenticate(HttpRequest request);
} }
} }

View File

@ -1,7 +1,11 @@
using MediaBrowser.Model.Services; using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Controller.Net namespace MediaBrowser.Controller.Net
{ {
/// <summary>
/// IAuthorization context.
/// </summary>
public interface IAuthorizationContext public interface IAuthorizationContext
{ {
/// <summary> /// <summary>
@ -17,5 +21,12 @@ namespace MediaBrowser.Controller.Net
/// <param name="requestContext">The request context.</param> /// <param name="requestContext">The request context.</param>
/// <returns>AuthorizationInfo.</returns> /// <returns>AuthorizationInfo.</returns>
AuthorizationInfo GetAuthorizationInfo(IRequest requestContext); AuthorizationInfo GetAuthorizationInfo(IRequest requestContext);
/// <summary>
/// Gets the authorization information.
/// </summary>
/// <param name="requestContext">The request context.</param>
/// <returns>AuthorizationInfo.</returns>
AuthorizationInfo GetAuthorizationInfo(HttpRequest requestContext);
} }
} }

View File

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

View File

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

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

View File

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

View File

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

View File

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

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