Merge branch 'master' into subtitle-display-title

This commit is contained in:
redSpoutnik
2019-03-16 17:54:57 +01:00
committed by GitHub
378 changed files with 3967 additions and 22242 deletions

View File

@@ -30,13 +30,10 @@ namespace Emby.Server.Implementations.Activity
public class ActivityLogEntryPoint : IServerEntryPoint
{
private readonly IInstallationManager _installationManager;
//private readonly ILogger _logger;
private readonly ISessionManager _sessionManager;
private readonly ITaskManager _taskManager;
private readonly IActivityManager _activityManager;
private readonly ILocalizationManager _localization;
private readonly ILibraryManager _libraryManager;
private readonly ISubtitleManager _subManager;
private readonly IUserManager _userManager;
@@ -61,41 +58,37 @@ namespace Emby.Server.Implementations.Activity
public Task RunAsync()
{
_taskManager.TaskCompleted += _taskManager_TaskCompleted;
_taskManager.TaskCompleted += OnTaskCompleted;
_installationManager.PluginInstalled += _installationManager_PluginInstalled;
_installationManager.PluginUninstalled += _installationManager_PluginUninstalled;
_installationManager.PluginUpdated += _installationManager_PluginUpdated;
_installationManager.PackageInstallationFailed += _installationManager_PackageInstallationFailed;
_installationManager.PluginInstalled += OnPluginInstalled;
_installationManager.PluginUninstalled += OnPluginUninstalled;
_installationManager.PluginUpdated += OnPluginUpdated;
_installationManager.PackageInstallationFailed += OnPackageInstallationFailed;
_sessionManager.SessionStarted += _sessionManager_SessionStarted;
_sessionManager.AuthenticationFailed += _sessionManager_AuthenticationFailed;
_sessionManager.AuthenticationSucceeded += _sessionManager_AuthenticationSucceeded;
_sessionManager.SessionEnded += _sessionManager_SessionEnded;
_sessionManager.SessionStarted += OnSessionStarted;
_sessionManager.AuthenticationFailed += OnAuthenticationFailed;
_sessionManager.AuthenticationSucceeded += OnAuthenticationSucceeded;
_sessionManager.SessionEnded += OnSessionEnded;
_sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
_sessionManager.PlaybackStopped += _sessionManager_PlaybackStopped;
_sessionManager.PlaybackStart += OnPlaybackStart;
_sessionManager.PlaybackStopped += OnPlaybackStopped;
//_subManager.SubtitlesDownloaded += _subManager_SubtitlesDownloaded;
_subManager.SubtitleDownloadFailure += _subManager_SubtitleDownloadFailure;
_subManager.SubtitleDownloadFailure += OnSubtitleDownloadFailure;
_userManager.UserCreated += _userManager_UserCreated;
_userManager.UserPasswordChanged += _userManager_UserPasswordChanged;
_userManager.UserDeleted += _userManager_UserDeleted;
_userManager.UserPolicyUpdated += _userManager_UserPolicyUpdated;
_userManager.UserLockedOut += _userManager_UserLockedOut;
_userManager.UserCreated += OnUserCreated;
_userManager.UserPasswordChanged += OnUserPasswordChanged;
_userManager.UserDeleted += OnUserDeleted;
_userManager.UserPolicyUpdated += OnUserPolicyUpdated;
_userManager.UserLockedOut += OnUserLockedOut;
//_config.ConfigurationUpdated += _config_ConfigurationUpdated;
//_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
_deviceManager.CameraImageUploaded += OnCameraImageUploaded;
_deviceManager.CameraImageUploaded += _deviceManager_CameraImageUploaded;
_appHost.ApplicationUpdated += _appHost_ApplicationUpdated;
_appHost.ApplicationUpdated += OnApplicationUpdated;
return Task.CompletedTask;
}
void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
private void OnCameraImageUploaded(object sender, GenericEventArgs<CameraImageUploadInfo> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -104,7 +97,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _userManager_UserLockedOut(object sender, GenericEventArgs<User> e)
private void OnUserLockedOut(object sender, GenericEventArgs<User> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -114,7 +107,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _subManager_SubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
private void OnSubtitleDownloadFailure(object sender, SubtitleDownloadFailureEventArgs e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -125,7 +118,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _sessionManager_PlaybackStopped(object sender, PlaybackStopEventArgs e)
private void OnPlaybackStopped(object sender, PlaybackStopEventArgs e)
{
var item = e.MediaInfo;
@@ -146,7 +139,7 @@ namespace Emby.Server.Implementations.Activity
return;
}
var user = e.Users.First();
var user = e.Users[0];
CreateLogEntry(new ActivityLogEntry
{
@@ -156,7 +149,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _sessionManager_PlaybackStart(object sender, PlaybackProgressEventArgs e)
private void OnPlaybackStart(object sender, PlaybackProgressEventArgs e)
{
var item = e.MediaInfo;
@@ -232,7 +225,7 @@ namespace Emby.Server.Implementations.Activity
return null;
}
void _sessionManager_SessionEnded(object sender, SessionEventArgs e)
private void OnSessionEnded(object sender, SessionEventArgs e)
{
string name;
var session = e.SessionInfo;
@@ -258,7 +251,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _sessionManager_AuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
private void OnAuthenticationSucceeded(object sender, GenericEventArgs<AuthenticationResult> e)
{
var user = e.Argument.User;
@@ -271,7 +264,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _sessionManager_AuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
private void OnAuthenticationFailed(object sender, GenericEventArgs<AuthenticationRequest> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -282,7 +275,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _appHost_ApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
private void OnApplicationUpdated(object sender, GenericEventArgs<PackageVersionInfo> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -292,25 +285,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
{
CreateLogEntry(new ActivityLogEntry
{
Name = string.Format(_localization.GetLocalizedString("MessageNamedServerConfigurationUpdatedWithValue"), e.Key),
Type = "NamedConfigurationUpdated"
});
}
void _config_ConfigurationUpdated(object sender, EventArgs e)
{
CreateLogEntry(new ActivityLogEntry
{
Name = _localization.GetLocalizedString("MessageServerConfigurationUpdated"),
Type = "ServerConfigurationUpdated"
});
}
void _userManager_UserPolicyUpdated(object sender, GenericEventArgs<User> e)
private void OnUserPolicyUpdated(object sender, GenericEventArgs<User> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -320,7 +295,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _userManager_UserDeleted(object sender, GenericEventArgs<User> e)
private void OnUserDeleted(object sender, GenericEventArgs<User> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -329,7 +304,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _userManager_UserPasswordChanged(object sender, GenericEventArgs<User> e)
private void OnUserPasswordChanged(object sender, GenericEventArgs<User> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -339,7 +314,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _userManager_UserCreated(object sender, GenericEventArgs<User> e)
private void OnUserCreated(object sender, GenericEventArgs<User> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -349,18 +324,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _subManager_SubtitlesDownloaded(object sender, SubtitleDownloadEventArgs e)
{
CreateLogEntry(new ActivityLogEntry
{
Name = string.Format(_localization.GetLocalizedString("SubtitlesDownloadedForItem"), Notifications.Notifications.GetItemName(e.Item)),
Type = "SubtitlesDownloaded",
ItemId = e.Item.Id.ToString("N"),
ShortOverview = string.Format(_localization.GetLocalizedString("ProviderValue"), e.Provider)
});
}
void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
private void OnSessionStarted(object sender, SessionEventArgs e)
{
string name;
var session = e.SessionInfo;
@@ -386,7 +350,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _installationManager_PluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
private void OnPluginUpdated(object sender, GenericEventArgs<Tuple<IPlugin, PackageVersionInfo>> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -397,7 +361,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _installationManager_PluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
private void OnPluginUninstalled(object sender, GenericEventArgs<IPlugin> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -406,7 +370,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _installationManager_PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
private void OnPluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> e)
{
CreateLogEntry(new ActivityLogEntry
{
@@ -416,7 +380,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _installationManager_PackageInstallationFailed(object sender, InstallationFailedEventArgs e)
private void OnPackageInstallationFailed(object sender, InstallationFailedEventArgs e)
{
var installationInfo = e.InstallationInfo;
@@ -429,7 +393,7 @@ namespace Emby.Server.Implementations.Activity
});
}
void _taskManager_TaskCompleted(object sender, TaskCompletionEventArgs e)
private void OnTaskCompleted(object sender, TaskCompletionEventArgs e)
{
var result = e.Result;
var task = e.Task;
@@ -468,48 +432,36 @@ namespace Emby.Server.Implementations.Activity
}
private void CreateLogEntry(ActivityLogEntry entry)
{
try
{
_activityManager.Create(entry);
}
catch
{
// Logged at lower levels
}
}
=> _activityManager.Create(entry);
public void Dispose()
{
_taskManager.TaskCompleted -= _taskManager_TaskCompleted;
_taskManager.TaskCompleted -= OnTaskCompleted;
_installationManager.PluginInstalled -= _installationManager_PluginInstalled;
_installationManager.PluginUninstalled -= _installationManager_PluginUninstalled;
_installationManager.PluginUpdated -= _installationManager_PluginUpdated;
_installationManager.PackageInstallationFailed -= _installationManager_PackageInstallationFailed;
_installationManager.PluginInstalled -= OnPluginInstalled;
_installationManager.PluginUninstalled -= OnPluginUninstalled;
_installationManager.PluginUpdated -= OnPluginUpdated;
_installationManager.PackageInstallationFailed -= OnPackageInstallationFailed;
_sessionManager.SessionStarted -= _sessionManager_SessionStarted;
_sessionManager.AuthenticationFailed -= _sessionManager_AuthenticationFailed;
_sessionManager.AuthenticationSucceeded -= _sessionManager_AuthenticationSucceeded;
_sessionManager.SessionEnded -= _sessionManager_SessionEnded;
_sessionManager.SessionStarted -= OnSessionStarted;
_sessionManager.AuthenticationFailed -= OnAuthenticationFailed;
_sessionManager.AuthenticationSucceeded -= OnAuthenticationSucceeded;
_sessionManager.SessionEnded -= OnSessionEnded;
_sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
_sessionManager.PlaybackStopped -= _sessionManager_PlaybackStopped;
_sessionManager.PlaybackStart -= OnPlaybackStart;
_sessionManager.PlaybackStopped -= OnPlaybackStopped;
_subManager.SubtitleDownloadFailure -= _subManager_SubtitleDownloadFailure;
_subManager.SubtitleDownloadFailure -= OnSubtitleDownloadFailure;
_userManager.UserCreated -= _userManager_UserCreated;
_userManager.UserPasswordChanged -= _userManager_UserPasswordChanged;
_userManager.UserDeleted -= _userManager_UserDeleted;
_userManager.UserPolicyUpdated -= _userManager_UserPolicyUpdated;
_userManager.UserLockedOut -= _userManager_UserLockedOut;
_userManager.UserCreated -= OnUserCreated;
_userManager.UserPasswordChanged -= OnUserPasswordChanged;
_userManager.UserDeleted -= OnUserDeleted;
_userManager.UserPolicyUpdated -= OnUserPolicyUpdated;
_userManager.UserLockedOut -= OnUserLockedOut;
_config.ConfigurationUpdated -= _config_ConfigurationUpdated;
_config.NamedConfigurationUpdated -= _config_NamedConfigurationUpdated;
_deviceManager.CameraImageUploaded -= OnCameraImageUploaded;
_deviceManager.CameraImageUploaded -= _deviceManager_CameraImageUploaded;
_appHost.ApplicationUpdated -= _appHost_ApplicationUpdated;
_appHost.ApplicationUpdated -= OnApplicationUpdated;
}
/// <summary>
@@ -531,6 +483,7 @@ namespace Emby.Server.Implementations.Activity
values.Add(CreateValueString(years, "year"));
days = days % DaysInYear;
}
// Number of months
if (days >= DaysInMonth)
{
@@ -538,25 +491,39 @@ namespace Emby.Server.Implementations.Activity
values.Add(CreateValueString(months, "month"));
days = days % DaysInMonth;
}
// Number of days
if (days >= 1)
{
values.Add(CreateValueString(days, "day"));
}
// Number of hours
if (span.Hours >= 1)
{
values.Add(CreateValueString(span.Hours, "hour"));
}
// Number of minutes
if (span.Minutes >= 1)
{
values.Add(CreateValueString(span.Minutes, "minute"));
}
// Number of seconds (include when 0 if no other components included)
if (span.Seconds >= 1 || values.Count == 0)
{
values.Add(CreateValueString(span.Seconds, "second"));
}
// Combine values into string
var builder = new StringBuilder();
for (int i = 0; i < values.Count; i++)
{
if (builder.Length > 0)
{
builder.Append(i == values.Count - 1 ? " and " : ", ");
}
builder.Append(values[i]);
}
// Return result

View File

@@ -17,12 +17,14 @@ namespace Emby.Server.Implementations.AppBase
string programDataPath,
string logDirectoryPath,
string configurationDirectoryPath,
string cacheDirectoryPath)
string cacheDirectoryPath,
string webDirectoryPath)
{
ProgramDataPath = programDataPath;
LogDirectoryPath = logDirectoryPath;
ConfigurationDirectoryPath = configurationDirectoryPath;
CachePath = cacheDirectoryPath;
WebPath = webDirectoryPath;
DataPath = Path.Combine(ProgramDataPath, "data");
}
@@ -33,6 +35,12 @@ namespace Emby.Server.Implementations.AppBase
/// <value>The program data path.</value>
public string ProgramDataPath { get; private set; }
/// <summary>
/// Gets the path to the web UI resources folder
/// </summary>
/// <value>The web UI resources path.</value>
public string WebPath { get; set; }
/// <summary>
/// Gets the path to the system folder
/// </summary>

File diff suppressed because it is too large Load Diff

View File

@@ -36,7 +36,7 @@ namespace Emby.Server.Implementations.Collections
return base.Supports(item);
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var playlist = (BoxSet)item;
@@ -80,7 +80,7 @@ namespace Emby.Server.Implementations.Collections
.ToList();
}
protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
}

View File

@@ -6,7 +6,8 @@ namespace Emby.Server.Implementations
{
public static readonly Dictionary<string, string> Configuration = new Dictionary<string, string>
{
{"HttpListenerHost:DefaultRedirectPath", "web/index.html"}
{"HttpListenerHost:DefaultRedirectPath", "web/index.html"},
{"MusicBrainz:BaseUrl", "https://www.musicbrainz.org"}
};
}
}

View File

@@ -1,13 +1,49 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using MediaBrowser.Model.Cryptography;
namespace Emby.Server.Implementations.Cryptography
{
public class CryptographyProvider : ICryptoProvider
{
private static readonly HashSet<string> _supportedHashMethods = new HashSet<string>()
{
"MD5",
"System.Security.Cryptography.MD5",
"SHA",
"SHA1",
"System.Security.Cryptography.SHA1",
"SHA256",
"SHA-256",
"System.Security.Cryptography.SHA256",
"SHA384",
"SHA-384",
"System.Security.Cryptography.SHA384",
"SHA512",
"SHA-512",
"System.Security.Cryptography.SHA512"
};
public string DefaultHashMethod => "PBKDF2";
private RandomNumberGenerator _randomNumberGenerator;
private const int _defaultIterations = 1000;
public CryptographyProvider()
{
//FIXME: When we get DotNet Standard 2.1 we need to revisit how we do the crypto
//Currently supported hash methods from https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptoconfig?view=netcore-2.1
//there might be a better way to autogenerate this list as dotnet updates, but I couldn't find one
//Please note the default method of PBKDF2 is not included, it cannot be used to generate hashes cleanly as it is actually a pbkdf with sha1
_randomNumberGenerator = RandomNumberGenerator.Create();
}
public Guid GetMD5(string str)
{
return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
@@ -36,5 +72,98 @@ namespace Emby.Server.Implementations.Cryptography
return provider.ComputeHash(bytes);
}
}
public IEnumerable<string> GetSupportedHashMethods()
{
return _supportedHashMethods;
}
private byte[] PBKDF2(string method, byte[] bytes, byte[] salt, int iterations)
{
//downgrading for now as we need this library to be dotnetstandard compliant
//with this downgrade we'll add a check to make sure we're on the downgrade method at the moment
if (method == DefaultHashMethod)
{
using (var r = new Rfc2898DeriveBytes(bytes, salt, iterations))
{
return r.GetBytes(32);
}
}
throw new CryptographicException($"Cannot currently use PBKDF2 with requested hash method: {method}");
}
public byte[] ComputeHash(string hashMethod, byte[] bytes)
{
return ComputeHash(hashMethod, bytes, Array.Empty<byte>());
}
public byte[] ComputeHashWithDefaultMethod(byte[] bytes)
{
return ComputeHash(DefaultHashMethod, bytes);
}
public byte[] ComputeHash(string hashMethod, byte[] bytes, byte[] salt)
{
if (hashMethod == DefaultHashMethod)
{
return PBKDF2(hashMethod, bytes, salt, _defaultIterations);
}
else if (_supportedHashMethods.Contains(hashMethod))
{
using (var h = HashAlgorithm.Create(hashMethod))
{
if (salt.Length == 0)
{
return h.ComputeHash(bytes);
}
else
{
byte[] salted = new byte[bytes.Length + salt.Length];
Array.Copy(bytes, salted, bytes.Length);
Array.Copy(salt, 0, salted, bytes.Length, salt.Length);
return h.ComputeHash(salted);
}
}
}
else
{
throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
}
}
public byte[] ComputeHashWithDefaultMethod(byte[] bytes, byte[] salt)
{
return PBKDF2(DefaultHashMethod, bytes, salt, _defaultIterations);
}
public byte[] ComputeHash(PasswordHash hash)
{
int iterations = _defaultIterations;
if (!hash.Parameters.ContainsKey("iterations"))
{
hash.Parameters.Add("iterations", _defaultIterations.ToString(CultureInfo.InvariantCulture));
}
else
{
try
{
iterations = int.Parse(hash.Parameters["iterations"]);
}
catch (Exception e)
{
throw new InvalidDataException($"Couldn't successfully parse iterations value from string: {hash.Parameters["iterations"]}", e);
}
}
return PBKDF2(hash.Id, hash.HashBytes, hash.SaltBytes, iterations);
}
public byte[] GenerateSalt()
{
byte[] salt = new byte[64];
_randomNumberGenerator.GetBytes(salt);
return salt;
}
}
}

View File

@@ -25,7 +25,6 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Reflection;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using SQLitePCL.pretty;
@@ -69,7 +68,6 @@ namespace Emby.Server.Implementations.Data
IServerApplicationHost appHost,
IJsonSerializer jsonSerializer,
ILoggerFactory loggerFactory,
IAssemblyInfo assemblyInfo,
ILocalizationManager localization)
: base(loggerFactory.CreateLogger(nameof(SqliteItemRepository)))
{
@@ -86,7 +84,7 @@ namespace Emby.Server.Implementations.Data
_appHost = appHost;
_config = config;
_jsonSerializer = jsonSerializer;
_typeMapper = new TypeMapper(assemblyInfo);
_typeMapper = new TypeMapper();
_localization = localization;
DbFilePath = Path.Combine(_config.ApplicationPaths.DataPath, "library.db");

View File

@@ -55,6 +55,8 @@ namespace Emby.Server.Implementations.Data
{
TryMigrateToLocalUsersTable(connection);
}
RemoveEmptyPasswordHashes();
}
}
@@ -73,6 +75,38 @@ namespace Emby.Server.Implementations.Data
}
}
private void RemoveEmptyPasswordHashes()
{
foreach (var user in RetrieveAllUsers())
{
// If the user password is the sha1 hash of the empty string, remove it
if (!string.Equals(user.Password, "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal)
|| !string.Equals(user.Password, "$SHA1$DA39A3EE5E6B4B0D3255BFEF95601890AFD80709", StringComparison.Ordinal))
{
continue;
}
user.Password = null;
var serialized = _jsonSerializer.SerializeToBytes(user);
using (WriteLock.Write())
using (var connection = CreateConnection())
{
connection.RunInTransaction(db =>
{
using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
{
statement.TryBind("@InternalId", user.InternalId);
statement.TryBind("@data", serialized);
statement.MoveNext();
}
}, TransactionMode);
}
}
}
/// <summary>
/// Save a user in the repo
/// </summary>

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
using MediaBrowser.Model.Reflection;
namespace Emby.Server.Implementations.Data
{
@@ -10,16 +9,13 @@ namespace Emby.Server.Implementations.Data
/// </summary>
public class TypeMapper
{
private readonly IAssemblyInfo _assemblyInfo;
/// <summary>
/// This holds all the types in the running assemblies so that we can de-serialize properly when we don't have strong types
/// </summary>
private readonly ConcurrentDictionary<string, Type> _typeMap = new ConcurrentDictionary<string, Type>();
public TypeMapper(IAssemblyInfo assemblyInfo)
public TypeMapper()
{
_assemblyInfo = assemblyInfo;
}
/// <summary>
@@ -45,8 +41,7 @@ namespace Emby.Server.Implementations.Data
/// <returns>Type.</returns>
private Type LookupType(string typeName)
{
return _assemblyInfo
.GetCurrentAssemblies()
return AppDomain.CurrentDomain.GetAssemblies()
.Select(a => a.GetType(typeName))
.FirstOrDefault(t => t != null);
}

View File

@@ -9,14 +9,14 @@ namespace Emby.Server.Implementations.Diagnostics
{
public class CommonProcess : IProcess
{
public event EventHandler Exited;
private readonly ProcessOptions _options;
private readonly Process _process;
private bool _disposed = false;
private bool _hasExited;
public CommonProcess(ProcessOptions options)
{
_options = options;
StartInfo = options;
var startInfo = new ProcessStartInfo
{
@@ -27,10 +27,10 @@ namespace Emby.Server.Implementations.Diagnostics
CreateNoWindow = options.CreateNoWindow,
RedirectStandardError = options.RedirectStandardError,
RedirectStandardInput = options.RedirectStandardInput,
RedirectStandardOutput = options.RedirectStandardOutput
RedirectStandardOutput = options.RedirectStandardOutput,
ErrorDialog = options.ErrorDialog
};
startInfo.ErrorDialog = options.ErrorDialog;
if (options.IsHidden)
{
@@ -45,11 +45,22 @@ namespace Emby.Server.Implementations.Diagnostics
if (options.EnableRaisingEvents)
{
_process.EnableRaisingEvents = true;
_process.Exited += _process_Exited;
_process.Exited += OnProcessExited;
}
}
private bool _hasExited;
public event EventHandler Exited;
public ProcessOptions StartInfo { get; }
public StreamWriter StandardInput => _process.StandardInput;
public StreamReader StandardError => _process.StandardError;
public StreamReader StandardOutput => _process.StandardOutput;
public int ExitCode => _process.ExitCode;
private bool HasExited
{
get
@@ -72,25 +83,6 @@ namespace Emby.Server.Implementations.Diagnostics
}
}
private void _process_Exited(object sender, EventArgs e)
{
_hasExited = true;
if (Exited != null)
{
Exited(this, e);
}
}
public ProcessOptions StartInfo => _options;
public StreamWriter StandardInput => _process.StandardInput;
public StreamReader StandardError => _process.StandardError;
public StreamReader StandardOutput => _process.StandardOutput;
public int ExitCode => _process.ExitCode;
public void Start()
{
_process.Start();
@@ -108,7 +100,7 @@ namespace Emby.Server.Implementations.Diagnostics
public Task<bool> WaitForExitAsync(int timeMs)
{
//Note: For this function to work correctly, the option EnableRisingEvents needs to be set to true.
// Note: For this function to work correctly, the option EnableRisingEvents needs to be set to true.
if (HasExited)
{
@@ -130,7 +122,29 @@ namespace Emby.Server.Implementations.Diagnostics
public void Dispose()
{
_process.Dispose();
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_process?.Dispose();
}
_disposed = true;
}
private void OnProcessExited(object sender, EventArgs e)
{
_hasExited = true;
Exited?.Invoke(this, e);
}
}
}

View File

@@ -9,12 +9,10 @@
<ProjectReference Include="..\MediaBrowser.Providers\MediaBrowser.Providers.csproj" />
<ProjectReference Include="..\MediaBrowser.WebDashboard\MediaBrowser.WebDashboard.csproj" />
<ProjectReference Include="..\MediaBrowser.XbmcMetadata\MediaBrowser.XbmcMetadata.csproj" />
<ProjectReference Include="..\SocketHttpListener\SocketHttpListener.csproj" />
<ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj" />
<ProjectReference Include="..\Mono.Nat\Mono.Nat.csproj" />
<ProjectReference Include="..\MediaBrowser.Api\MediaBrowser.Api.csproj" />
<ProjectReference Include="..\MediaBrowser.LocalMetadata\MediaBrowser.LocalMetadata.csproj" />
<ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj" />
<ProjectReference Include="..\Emby.Photos\Emby.Photos.csproj" />
<ProjectReference Include="..\Emby.Drawing\Emby.Drawing.csproj" />
<ProjectReference Include="..\Emby.XmlTv\Emby.XmlTv\Emby.XmlTv.csproj" />
@@ -22,6 +20,14 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.2.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.2.0" />
@@ -40,6 +46,21 @@
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<!-- Code analysers-->
<ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.3" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2" />
<PackageReference Include="SerilogAnalyzer" Version="0.15.0" />
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="Localization\iso6392.txt" />
<EmbeddedResource Include="Localization\countries.json" />

View File

@@ -1,36 +0,0 @@
using System;
using System.Runtime.InteropServices;
using MediaBrowser.Model.System;
namespace Emby.Server.Implementations.EnvironmentInfo
{
public class EnvironmentInfo : IEnvironmentInfo
{
public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem)
{
OperatingSystem = operatingSystem;
}
public MediaBrowser.Model.System.OperatingSystem OperatingSystem { get; private set; }
public string OperatingSystemName
{
get
{
switch (OperatingSystem)
{
case MediaBrowser.Model.System.OperatingSystem.Android: return "Android";
case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD";
case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux";
case MediaBrowser.Model.System.OperatingSystem.OSX: return "macOS";
case MediaBrowser.Model.System.OperatingSystem.Windows: return "Windows";
default: throw new Exception($"Unknown OS {OperatingSystem}");
}
}
}
public string OperatingSystemVersion => Environment.OSVersion.Version.ToString() + " " + Environment.OSVersion.ServicePack.ToString();
public Architecture SystemArchitecture => RuntimeInformation.OSArchitecture;
}
}

View File

@@ -1,24 +0,0 @@
namespace Emby.Server.Implementations.FFMpeg
{
/// <summary>
/// Class FFMpegInfo
/// </summary>
public class FFMpegInfo
{
/// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
public string EncoderPath { get; set; }
/// <summary>
/// Gets or sets the probe path.
/// </summary>
/// <value>The probe path.</value>
public string ProbePath { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
/// <value>The version.</value>
public string Version { get; set; }
}
}

View File

@@ -1,17 +0,0 @@
namespace Emby.Server.Implementations.FFMpeg
{
public class FFMpegInstallInfo
{
public string Version { get; set; }
public string FFMpegFilename { get; set; }
public string FFProbeFilename { get; set; }
public string ArchiveType { get; set; }
public FFMpegInstallInfo()
{
Version = "Path";
FFMpegFilename = "ffmpeg";
FFProbeFilename = "ffprobe";
}
}
}

View File

@@ -1,132 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
namespace Emby.Server.Implementations.FFMpeg
{
public class FFMpegLoader
{
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
private readonly FFMpegInstallInfo _ffmpegInstallInfo;
public FFMpegLoader(IApplicationPaths appPaths, IFileSystem fileSystem, FFMpegInstallInfo ffmpegInstallInfo)
{
_appPaths = appPaths;
_fileSystem = fileSystem;
_ffmpegInstallInfo = ffmpegInstallInfo;
}
public FFMpegInfo GetFFMpegInfo(IStartupOptions options)
{
var customffMpegPath = options.FFmpegPath;
var customffProbePath = options.FFprobePath;
if (!string.IsNullOrWhiteSpace(customffMpegPath) && !string.IsNullOrWhiteSpace(customffProbePath))
{
return new FFMpegInfo
{
ProbePath = customffProbePath,
EncoderPath = customffMpegPath,
Version = "external"
};
}
var downloadInfo = _ffmpegInstallInfo;
var prebuiltFolder = _appPaths.ProgramSystemPath;
var prebuiltffmpeg = Path.Combine(prebuiltFolder, downloadInfo.FFMpegFilename);
var prebuiltffprobe = Path.Combine(prebuiltFolder, downloadInfo.FFProbeFilename);
if (File.Exists(prebuiltffmpeg) && File.Exists(prebuiltffprobe))
{
return new FFMpegInfo
{
ProbePath = prebuiltffprobe,
EncoderPath = prebuiltffmpeg,
Version = "external"
};
}
var version = downloadInfo.Version;
if (string.Equals(version, "0", StringComparison.OrdinalIgnoreCase))
{
return new FFMpegInfo();
}
var rootEncoderPath = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
var versionedDirectoryPath = Path.Combine(rootEncoderPath, version);
var info = new FFMpegInfo
{
ProbePath = Path.Combine(versionedDirectoryPath, downloadInfo.FFProbeFilename),
EncoderPath = Path.Combine(versionedDirectoryPath, downloadInfo.FFMpegFilename),
Version = version
};
Directory.CreateDirectory(versionedDirectoryPath);
var excludeFromDeletions = new List<string> { versionedDirectoryPath };
if (!File.Exists(info.ProbePath) || !File.Exists(info.EncoderPath))
{
// ffmpeg not present. See if there's an older version we can start with
var existingVersion = GetExistingVersion(info, rootEncoderPath);
// No older version. Need to download and block until complete
if (existingVersion == null)
{
return new FFMpegInfo();
}
else
{
info = existingVersion;
versionedDirectoryPath = Path.GetDirectoryName(info.EncoderPath);
excludeFromDeletions.Add(versionedDirectoryPath);
}
}
// Allow just one of these to be overridden, if desired.
if (!string.IsNullOrWhiteSpace(customffMpegPath))
{
info.EncoderPath = customffMpegPath;
}
if (!string.IsNullOrWhiteSpace(customffProbePath))
{
info.ProbePath = customffProbePath;
}
return info;
}
private FFMpegInfo GetExistingVersion(FFMpegInfo info, string rootEncoderPath)
{
var encoderFilename = Path.GetFileName(info.EncoderPath);
var probeFilename = Path.GetFileName(info.ProbePath);
foreach (var directory in _fileSystem.GetDirectoryPaths(rootEncoderPath))
{
var allFiles = _fileSystem.GetFilePaths(directory, true).ToList();
var encoder = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), encoderFilename, StringComparison.OrdinalIgnoreCase));
var probe = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), probeFilename, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrWhiteSpace(encoder) &&
!string.IsNullOrWhiteSpace(probe))
{
return new FFMpegInfo
{
EncoderPath = encoder,
ProbePath = probe,
Version = Path.GetFileName(Path.GetDirectoryName(probe))
};
}
}
return null;
}
}
}

View File

@@ -15,6 +15,7 @@ using MediaBrowser.Common.Net;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpClientManager
{
@@ -179,11 +180,11 @@ namespace Emby.Server.Implementations.HttpClientManager
foreach (var header in options.RequestHeaders)
{
if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
if (string.Equals(header.Key, HeaderNames.Accept, StringComparison.OrdinalIgnoreCase))
{
request.Accept = header.Value;
}
else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
else if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
{
SetUserAgent(request, header.Value);
hasUserAgent = true;
@@ -327,7 +328,6 @@ namespace Emby.Server.Implementations.HttpClientManager
}
httpWebRequest.ContentType = contentType;
httpWebRequest.ContentLength = bytes.Length;
(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
}
catch (Exception ex)

View File

@@ -5,15 +5,19 @@ using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer
{
public class FileWriter : IHttpResult
{
private readonly IStreamHelper _streamHelper;
private ILogger Logger { get; set; }
private readonly IFileSystem _fileSystem;
private string RangeHeader { get; set; }
private bool IsHeadRequest { get; set; }
@@ -42,25 +46,27 @@ namespace Emby.Server.Implementations.HttpServer
public string Path { get; set; }
public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem)
public FileWriter(string path, string contentType, string rangeHeader, ILogger logger, IFileSystem fileSystem, IStreamHelper streamHelper)
{
if (string.IsNullOrEmpty(contentType))
{
throw new ArgumentNullException(nameof(contentType));
}
_streamHelper = streamHelper;
_fileSystem = fileSystem;
Path = path;
Logger = logger;
RangeHeader = rangeHeader;
Headers["Content-Type"] = contentType;
Headers[HeaderNames.ContentType] = contentType;
TotalContentLength = fileSystem.GetFileInfo(path).Length;
Headers["Accept-Ranges"] = "bytes";
Headers[HeaderNames.AcceptRanges] = "bytes";
if (string.IsNullOrWhiteSpace(rangeHeader))
{
Headers["Content-Length"] = TotalContentLength.ToString(UsCulture);
StatusCode = HttpStatusCode.OK;
}
else
@@ -93,13 +99,10 @@ namespace Emby.Server.Implementations.HttpServer
RangeStart = requestedRange.Key;
RangeLength = 1 + RangeEnd - RangeStart;
// Content-Length is the length of what we're serving, not the original content
var lengthString = RangeLength.ToString(UsCulture);
Headers["Content-Length"] = lengthString;
var rangeString = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
Headers["Content-Range"] = rangeString;
var rangeString = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
Headers[HeaderNames.ContentRange] = rangeString;
Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Length: {2}, Content-Range: {3}", Path, RangeHeader, lengthString, rangeString);
Logger.LogInformation("Setting range response values for {0}. RangeRequest: {1} Content-Range: {2}", Path, RangeHeader, rangeString);
}
/// <summary>
@@ -145,8 +148,7 @@ namespace Emby.Server.Implementations.HttpServer
}
}
private string[] SkipLogExtensions = new string[]
{
private static readonly string[] SkipLogExtensions = {
".js",
".html",
".css"
@@ -163,8 +165,10 @@ namespace Emby.Server.Implementations.HttpServer
}
var path = Path;
var offset = RangeStart;
var count = RangeLength;
if (string.IsNullOrWhiteSpace(RangeHeader) || (RangeStart <= 0 && RangeEnd >= TotalContentLength - 1))
if (string.IsNullOrWhiteSpace(RangeHeader) || RangeStart <= 0 && RangeEnd >= TotalContentLength - 1)
{
var extension = System.IO.Path.GetExtension(path);
@@ -173,20 +177,15 @@ namespace Emby.Server.Implementations.HttpServer
Logger.LogDebug("Transmit file {0}", path);
}
//var count = FileShare == FileShareMode.ReadWrite ? TotalContentLength : 0;
await response.TransmitFile(path, 0, 0, FileShare, cancellationToken).ConfigureAwait(false);
return;
offset = 0;
count = 0;
}
await response.TransmitFile(path, RangeStart, RangeLength, FileShare, cancellationToken).ConfigureAwait(false);
await response.TransmitFile(path, offset, count, FileShare, _fileSystem, _streamHelper, cancellationToken).ConfigureAwait(false);
}
finally
{
if (OnComplete != null)
{
OnComplete();
}
OnComplete?.Invoke();
}
}
@@ -203,8 +202,5 @@ namespace Emby.Server.Implementations.HttpServer
get => (HttpStatusCode)Status;
set => Status = (int)value;
}
public string StatusDescription { get; set; }
}
}

View File

@@ -11,6 +11,7 @@ using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Net;
using Emby.Server.Implementations.Services;
using Emby.Server.Implementations.SocketSharp;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
@@ -20,6 +21,9 @@ using MediaBrowser.Model.Events;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServiceStack.Text.Jsv;
@@ -29,12 +33,8 @@ namespace Emby.Server.Implementations.HttpServer
public class HttpListenerHost : IHttpServer, IDisposable
{
private string DefaultRedirectPath { get; set; }
private readonly ILogger _logger;
public string[] UrlPrefixes { get; private set; }
private IHttpListener _listener;
public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
private readonly IServerConfigurationManager _config;
@@ -42,6 +42,7 @@ namespace Emby.Server.Implementations.HttpServer
private readonly IServerApplicationHost _appHost;
private readonly IJsonSerializer _jsonSerializer;
private readonly IXmlSerializer _xmlSerializer;
private readonly IHttpListener _socketListener;
private readonly Func<Type, Func<string, object>> _funcParseFn;
public Action<IRequest, IResponse, object>[] ResponseFilters { get; set; }
@@ -59,15 +60,18 @@ namespace Emby.Server.Implementations.HttpServer
IConfiguration configuration,
INetworkManager networkManager,
IJsonSerializer jsonSerializer,
IXmlSerializer xmlSerializer)
IXmlSerializer xmlSerializer,
IHttpListener socketListener)
{
_appHost = applicationHost;
_logger = loggerFactory.CreateLogger("HttpServer");
Logger = loggerFactory.CreateLogger("HttpServer");
_config = config;
DefaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
_networkManager = networkManager;
_jsonSerializer = jsonSerializer;
_xmlSerializer = xmlSerializer;
_socketListener = socketListener;
_socketListener.WebSocketConnected = OnWebSocketConnected;
_funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
@@ -77,7 +81,7 @@ namespace Emby.Server.Implementations.HttpServer
public string GlobalResponse { get; set; }
protected ILogger Logger => _logger;
protected ILogger Logger { get; }
public object CreateInstance(Type type)
{
@@ -143,11 +147,11 @@ namespace Emby.Server.Implementations.HttpServer
return;
}
var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, Logger)
{
OnReceive = ProcessWebSocketMessageReceived,
Url = e.Url,
QueryString = e.QueryString ?? new QueryParamCollection()
QueryString = e.QueryString ?? new QueryCollection()
};
connection.Closed += Connection_Closed;
@@ -212,16 +216,16 @@ namespace Emby.Server.Implementations.HttpServer
if (logExceptionStackTrace)
{
_logger.LogError(ex, "Error processing request");
Logger.LogError(ex, "Error processing request");
}
else if (logExceptionMessage)
{
_logger.LogError(ex.Message);
Logger.LogError(ex.Message);
}
var httpRes = httpReq.Response;
if (httpRes.IsClosed)
if (httpRes.OriginalResponse.HasStarted)
{
return;
}
@@ -234,7 +238,7 @@ namespace Emby.Server.Implementations.HttpServer
}
catch (Exception errorEx)
{
_logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
Logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
}
}
@@ -277,14 +281,6 @@ namespace Emby.Server.Implementations.HttpServer
}
}
if (_listener != null)
{
_logger.LogInformation("Stopping HttpListener...");
var task = _listener.Stop();
Task.WaitAll(task);
_logger.LogInformation("HttpListener stopped");
}
}
public static string RemoveQueryStringByKey(string url, string key)
@@ -292,7 +288,7 @@ namespace Emby.Server.Implementations.HttpServer
var uri = new Uri(url);
// this gets all the query string key value pairs as a collection
var newQueryString = MyHttpUtility.ParseQueryString(uri.Query);
var newQueryString = QueryHelpers.ParseQuery(uri.Query);
var originalCount = newQueryString.Count;
@@ -313,7 +309,7 @@ namespace Emby.Server.Implementations.HttpServer
string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
return newQueryString.Count > 0
? string.Format("{0}?{1}", pagePathWithoutQueryString, newQueryString)
? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
: pagePathWithoutQueryString;
}
@@ -422,7 +418,7 @@ namespace Emby.Server.Implementations.HttpServer
/// <summary>
/// Overridable method that can be used to implement a custom hnandler
/// </summary>
protected async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
@@ -599,17 +595,15 @@ namespace Emby.Server.Implementations.HttpServer
}
finally
{
httpRes.Close();
stopWatch.Stop();
var elapsed = stopWatch.Elapsed;
if (elapsed.TotalMilliseconds > 500)
{
_logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
Logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
}
else
{
_logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
Logger.LogDebug("HTTP Response {StatusCode} to {RemoteIp}. Time: {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
}
}
}
@@ -622,7 +616,7 @@ namespace Emby.Server.Implementations.HttpServer
var pathParts = pathInfo.TrimStart('/').Split('/');
if (pathParts.Length == 0)
{
_logger.LogError("Path parts empty for PathInfo: {PathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
Logger.LogError("Path parts empty for PathInfo: {PathInfo}, Url: {RawUrl}", pathInfo, httpReq.RawUrl);
return null;
}
@@ -636,15 +630,13 @@ namespace Emby.Server.Implementations.HttpServer
};
}
_logger.LogError("Could not find handler for {PathInfo}", pathInfo);
Logger.LogError("Could not find handler for {PathInfo}", pathInfo);
return null;
}
private static Task Write(IResponse response, string text)
{
var bOutput = Encoding.UTF8.GetBytes(text);
response.SetContentLength(bOutput.Length);
return response.OutputStream.WriteAsync(bOutput, 0, bOutput.Length);
}
@@ -663,6 +655,7 @@ namespace Emby.Server.Implementations.HttpServer
}
else
{
// TODO what is this?
var httpsUrl = url
.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase)
.Replace(":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture), ":" + _config.Configuration.PublicHttpsPort.ToString(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase);
@@ -683,13 +676,15 @@ namespace Emby.Server.Implementations.HttpServer
/// Adds the rest handlers.
/// </summary>
/// <param name="services">The services.</param>
public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners)
/// <param name="listeners"></param>
/// <param name="urlPrefixes"></param>
public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
{
_webSocketListeners = listeners.ToArray();
UrlPrefixes = urlPrefixes.ToArray();
ServiceController = new ServiceController();
_logger.LogInformation("Calling ServiceStack AppHost.Init");
Logger.LogInformation("Calling ServiceStack AppHost.Init");
var types = services.Select(r => r.GetType()).ToArray();
@@ -697,7 +692,7 @@ namespace Emby.Server.Implementations.HttpServer
ResponseFilters = new Action<IRequest, IResponse, object>[]
{
new ResponseFilter(_logger).FilterResponse
new ResponseFilter(Logger).FilterResponse
};
}
@@ -759,8 +754,12 @@ namespace Emby.Server.Implementations.HttpServer
return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
}
//TODO Add Jellyfin Route Path Normalizer
public Task ProcessWebSocketRequest(HttpContext context)
{
return _socketListener.ProcessWebSocketRequest(context);
}
//TODO Add Jellyfin Route Path Normalizer
private static string NormalizeEmbyRoutePath(string path)
{
if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
@@ -793,6 +792,7 @@ namespace Emby.Server.Implementations.HttpServer
private bool _disposed;
private readonly object _disposeLock = new object();
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
@@ -821,7 +821,7 @@ namespace Emby.Server.Implementations.HttpServer
return Task.CompletedTask;
}
_logger.LogDebug("Websocket message received: {0}", result.MessageType);
Logger.LogDebug("Websocket message received: {0}", result.MessageType);
var tasks = _webSocketListeners.Select(i => Task.Run(async () =>
{
@@ -831,7 +831,7 @@ namespace Emby.Server.Implementations.HttpServer
}
catch (Exception ex)
{
_logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
Logger.LogError(ex, "{0} failed processing WebSocket message {1}", i.GetType().Name, result.MessageType ?? string.Empty);
}
}));
@@ -842,18 +842,5 @@ namespace Emby.Server.Implementations.HttpServer
{
Dispose(true);
}
public void StartServer(string[] urlPrefixes, IHttpListener httpListener)
{
UrlPrefixes = urlPrefixes;
_listener = httpListener;
_listener.WebSocketConnected = OnWebSocketConnected;
_listener.ErrorHandler = ErrorHandler;
_listener.RequestHandler = RequestHandler;
_listener.Start(UrlPrefixes);
}
}
}

View File

@@ -16,6 +16,8 @@ using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using IRequest = MediaBrowser.Model.Services.IRequest;
using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
@@ -32,17 +34,16 @@ namespace Emby.Server.Implementations.HttpServer
private readonly ILogger _logger;
private readonly IFileSystem _fileSystem;
private readonly IJsonSerializer _jsonSerializer;
private IBrotliCompressor _brotliCompressor;
private readonly IStreamHelper _streamHelper;
/// <summary>
/// Initializes a new instance of the <see cref="HttpResultFactory" /> class.
/// </summary>
public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IBrotliCompressor brotliCompressor)
public HttpResultFactory(ILoggerFactory loggerfactory, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IStreamHelper streamHelper)
{
_fileSystem = fileSystem;
_jsonSerializer = jsonSerializer;
_brotliCompressor = brotliCompressor;
_streamHelper = streamHelper;
_logger = loggerfactory.CreateLogger("HttpResultFactory");
}
@@ -76,7 +77,7 @@ namespace Emby.Server.Implementations.HttpServer
public object GetRedirectResult(string url)
{
var responseHeaders = new Dictionary<string, string>();
responseHeaders["Location"] = url;
responseHeaders[HeaderNames.Location] = url;
var result = new HttpResult(Array.Empty<byte>(), "text/plain", HttpStatusCode.Redirect);
@@ -97,9 +98,9 @@ namespace Emby.Server.Implementations.HttpServer
responseHeaders = new Dictionary<string, string>();
}
if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string expires))
if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string expires))
{
responseHeaders["Expires"] = "-1";
responseHeaders[HeaderNames.Expires] = "-1";
}
AddResponseHeaders(result, responseHeaders);
@@ -131,7 +132,7 @@ namespace Emby.Server.Implementations.HttpServer
content = Array.Empty<byte>();
}
result = new StreamWriter(content, contentType, contentLength);
result = new StreamWriter(content, contentType);
}
else
{
@@ -143,9 +144,9 @@ namespace Emby.Server.Implementations.HttpServer
responseHeaders = new Dictionary<string, string>();
}
if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
{
responseHeaders["Expires"] = "-1";
responseHeaders[HeaderNames.Expires] = "-1";
}
AddResponseHeaders(result, responseHeaders);
@@ -175,7 +176,7 @@ namespace Emby.Server.Implementations.HttpServer
bytes = Array.Empty<byte>();
}
result = new StreamWriter(bytes, contentType, contentLength);
result = new StreamWriter(bytes, contentType);
}
else
{
@@ -187,9 +188,9 @@ namespace Emby.Server.Implementations.HttpServer
responseHeaders = new Dictionary<string, string>();
}
if (addCachePrevention && !responseHeaders.TryGetValue("Expires", out string _))
if (addCachePrevention && !responseHeaders.TryGetValue(HeaderNames.Expires, out string _))
{
responseHeaders["Expires"] = "-1";
responseHeaders[HeaderNames.Expires] = "-1";
}
AddResponseHeaders(result, responseHeaders);
@@ -214,7 +215,7 @@ namespace Emby.Server.Implementations.HttpServer
responseHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
responseHeaders["Expires"] = "-1";
responseHeaders[HeaderNames.Expires] = "-1";
return ToOptimizedResultInternal(requestContext, result, responseHeaders);
}
@@ -246,9 +247,9 @@ namespace Emby.Server.Implementations.HttpServer
private static string GetCompressionType(IRequest request)
{
var acceptEncoding = request.Headers["Accept-Encoding"];
var acceptEncoding = request.Headers[HeaderNames.AcceptEncoding].ToString();
if (acceptEncoding != null)
if (string.IsNullOrEmpty(acceptEncoding))
{
//if (_brotliCompressor != null && acceptEncoding.IndexOf("br", StringComparison.OrdinalIgnoreCase) != -1)
// return "br";
@@ -326,21 +327,21 @@ namespace Emby.Server.Implementations.HttpServer
}
content = Compress(content, requestedCompressionType);
responseHeaders["Content-Encoding"] = requestedCompressionType;
responseHeaders[HeaderNames.ContentEncoding] = requestedCompressionType;
responseHeaders["Vary"] = "Accept-Encoding";
responseHeaders[HeaderNames.Vary] = HeaderNames.AcceptEncoding;
var contentLength = content.Length;
if (isHeadRequest)
{
var result = new StreamWriter(Array.Empty<byte>(), contentType, contentLength);
var result = new StreamWriter(Array.Empty<byte>(), contentType);
AddResponseHeaders(result, responseHeaders);
return result;
}
else
{
var result = new StreamWriter(content, contentType, contentLength);
var result = new StreamWriter(content, contentType);
AddResponseHeaders(result, responseHeaders);
return result;
}
@@ -348,11 +349,6 @@ namespace Emby.Server.Implementations.HttpServer
private byte[] Compress(byte[] bytes, string compressionType)
{
if (string.Equals(compressionType, "br", StringComparison.OrdinalIgnoreCase))
{
return CompressBrotli(bytes);
}
if (string.Equals(compressionType, "deflate", StringComparison.OrdinalIgnoreCase))
{
return Deflate(bytes);
@@ -366,11 +362,6 @@ namespace Emby.Server.Implementations.HttpServer
throw new NotSupportedException(compressionType);
}
private byte[] CompressBrotli(byte[] bytes)
{
return _brotliCompressor.Compress(bytes);
}
private static byte[] Deflate(byte[] bytes)
{
// In .NET FX incompat-ville, you can't access compressed bytes without closing DeflateStream
@@ -424,12 +415,12 @@ namespace Emby.Server.Implementations.HttpServer
/// </summary>
private object GetCachedResult(IRequest requestContext, IDictionary<string, string> responseHeaders, StaticResultOptions options)
{
bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).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);
if (!noCache)
{
DateTime.TryParse(requestContext.Headers.Get("If-Modified-Since"), out var ifModifiedSinceHeader);
DateTime.TryParse(requestContext.Headers[HeaderNames.IfModifiedSince], out var ifModifiedSinceHeader);
if (IsNotModified(ifModifiedSinceHeader, options.CacheDuration, options.DateLastModified))
{
@@ -530,7 +521,7 @@ namespace Emby.Server.Implementations.HttpServer
options.ResponseHeaders = options.ResponseHeaders ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var contentType = options.ContentType;
if (!string.IsNullOrEmpty(requestContext.Headers.Get("If-Modified-Since")))
if (!StringValues.IsNullOrEmpty(requestContext.Headers[HeaderNames.IfModifiedSince]))
{
// See if the result is already cached in the browser
var result = GetCachedResult(requestContext, options.ResponseHeaders, options);
@@ -548,11 +539,11 @@ namespace Emby.Server.Implementations.HttpServer
AddCachingHeaders(responseHeaders, options.CacheDuration, false, options.DateLastModified);
AddAgeHeader(responseHeaders, options.DateLastModified);
var rangeHeader = requestContext.Headers.Get("Range");
var rangeHeader = requestContext.Headers[HeaderNames.Range];
if (!isHeadRequest && !string.IsNullOrEmpty(options.Path))
{
var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem)
var hasHeaders = new FileWriter(options.Path, contentType, rangeHeader, _logger, _fileSystem, _streamHelper)
{
OnComplete = options.OnComplete,
OnError = options.OnError,
@@ -590,11 +581,6 @@ namespace Emby.Server.Implementations.HttpServer
}
else
{
if (totalContentLength.HasValue)
{
responseHeaders["Content-Length"] = totalContentLength.Value.ToString(UsCulture);
}
if (isHeadRequest)
{
using (stream)
@@ -614,11 +600,6 @@ namespace Emby.Server.Implementations.HttpServer
}
}
/// <summary>
/// The us culture
/// </summary>
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary>
/// Adds the caching responseHeaders.
/// </summary>
@@ -627,23 +608,23 @@ namespace Emby.Server.Implementations.HttpServer
{
if (noCache)
{
responseHeaders["Cache-Control"] = "no-cache, no-store, must-revalidate";
responseHeaders["pragma"] = "no-cache, no-store, must-revalidate";
responseHeaders[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
responseHeaders[HeaderNames.Pragma] = "no-cache, no-store, must-revalidate";
return;
}
if (cacheDuration.HasValue)
{
responseHeaders["Cache-Control"] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
responseHeaders[HeaderNames.CacheControl] = "public, max-age=" + cacheDuration.Value.TotalSeconds;
}
else
{
responseHeaders["Cache-Control"] = "public";
responseHeaders[HeaderNames.CacheControl] = "public";
}
if (lastModifiedDate.HasValue)
{
responseHeaders["Last-Modified"] = lastModifiedDate.ToString();
responseHeaders[HeaderNames.LastModified] = lastModifiedDate.ToString();
}
}
@@ -656,7 +637,7 @@ namespace Emby.Server.Implementations.HttpServer
{
if (lastDateModified.HasValue)
{
responseHeaders["Age"] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
responseHeaders[HeaderNames.Age] = Convert.ToInt64((DateTime.UtcNow - lastDateModified.Value).TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
}
@@ -714,9 +695,4 @@ namespace Emby.Server.Implementations.HttpServer
}
}
}
public interface IBrotliCompressor
{
byte[] Compress(byte[] content);
}
}

View File

@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Net;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
namespace Emby.Server.Implementations.HttpServer
{
@@ -28,21 +27,11 @@ namespace Emby.Server.Implementations.HttpServer
/// <value>The web socket handler.</value>
Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
/// <summary>
/// Gets or sets the web socket connecting.
/// </summary>
/// <value>The web socket connecting.</value>
Action<WebSocketConnectingEventArgs> WebSocketConnecting { get; set; }
/// <summary>
/// Starts this instance.
/// </summary>
/// <param name="urlPrefixes">The URL prefixes.</param>
void Start(IEnumerable<string> urlPrefixes);
/// <summary>
/// Stops this instance.
/// </summary>
Task Stop();
Task ProcessWebSocketRequest(HttpContext ctx);
}
}

View File

@@ -7,6 +7,7 @@ using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer
{
@@ -66,8 +67,8 @@ namespace Emby.Server.Implementations.HttpServer
this._logger = logger;
ContentType = contentType;
Headers["Content-Type"] = contentType;
Headers["Accept-Ranges"] = "bytes";
Headers[HeaderNames.ContentType] = contentType;
Headers[HeaderNames.AcceptRanges] = "bytes";
StatusCode = HttpStatusCode.PartialContent;
SetRangeValues(contentLength);
@@ -95,9 +96,7 @@ namespace Emby.Server.Implementations.HttpServer
RangeStart = requestedRange.Key;
RangeLength = 1 + RangeEnd - RangeStart;
// Content-Length is the length of what we're serving, not the original content
Headers["Content-Length"] = RangeLength.ToString(UsCulture);
Headers["Content-Range"] = string.Format("bytes {0}-{1}/{2}", RangeStart, RangeEnd, TotalContentLength);
Headers[HeaderNames.ContentRange] = $"bytes {RangeStart}-{RangeEnd}/{TotalContentLength}";
if (RangeStart > 0 && SourceStream.CanSeek)
{

View File

@@ -3,6 +3,7 @@ using System.Globalization;
using System.Text;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer
{
@@ -25,7 +26,7 @@ namespace Emby.Server.Implementations.HttpServer
public void FilterResponse(IRequest req, IResponse res, object dto)
{
// Try to prevent compatibility view
res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, 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, X-Emby-Authorization");
res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-MD5, Content-Range, Content-Type, 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, X-Emby-Authorization");
res.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
res.AddHeader("Access-Control-Allow-Origin", "*");
@@ -44,20 +45,19 @@ namespace Emby.Server.Implementations.HttpServer
if (dto is IHasHeaders hasHeaders)
{
if (!hasHeaders.Headers.ContainsKey("Server"))
if (!hasHeaders.Headers.ContainsKey(HeaderNames.Server))
{
hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50";
hasHeaders.Headers[HeaderNames.Server] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50";
}
// Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength)
if (hasHeaders.Headers.TryGetValue(HeaderNames.ContentLength, out string contentLength)
&& !string.IsNullOrEmpty(contentLength))
{
var length = long.Parse(contentLength, UsCulture);
if (length > 0)
{
res.SetContentLength(length);
res.SendChunked = false;
}
}

View File

@@ -5,6 +5,7 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.Services;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer.Security
{
@@ -176,7 +177,7 @@ namespace Emby.Server.Implementations.HttpServer.Security
if (string.IsNullOrEmpty(auth))
{
auth = httpReq.Headers["Authorization"];
auth = httpReq.Headers[HeaderNames.Authorization];
}
return GetAuthorization(auth);

View File

@@ -5,7 +5,7 @@ using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.HttpServer
{
@@ -52,12 +52,7 @@ namespace Emby.Server.Implementations.HttpServer
SourceStream = source;
Headers["Content-Type"] = contentType;
if (source.CanSeek)
{
Headers["Content-Length"] = source.Length.ToString(UsCulture);
}
Headers[HeaderNames.ContentType] = contentType;
}
/// <summary>
@@ -65,8 +60,7 @@ namespace Emby.Server.Implementations.HttpServer
/// </summary>
/// <param name="source">The source.</param>
/// <param name="contentType">Type of the content.</param>
/// <param name="logger">The logger.</param>
public StreamWriter(byte[] source, string contentType, int contentLength)
public StreamWriter(byte[] source, string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
@@ -75,9 +69,7 @@ namespace Emby.Server.Implementations.HttpServer
SourceBytes = source;
Headers["Content-Type"] = contentType;
Headers["Content-Length"] = contentLength.ToString(UsCulture);
Headers[HeaderNames.ContentType] = contentType;
}
public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken)

View File

@@ -8,6 +8,7 @@ using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using UtfUnknown;
@@ -67,7 +68,7 @@ namespace Emby.Server.Implementations.HttpServer
/// Gets or sets the query string.
/// </summary>
/// <value>The query string.</value>
public QueryParamCollection QueryString { get; set; }
public IQueryCollection QueryString { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
@@ -101,12 +102,6 @@ namespace Emby.Server.Implementations.HttpServer
_socket = socket;
_socket.OnReceiveBytes = OnReceiveInternal;
var memorySocket = socket as IMemoryWebSocket;
if (memorySocket != null)
{
memorySocket.OnReceiveMemoryBytes = OnReceiveInternal;
}
RemoteEndPoint = remoteEndPoint;
_logger = logger;
@@ -142,34 +137,6 @@ namespace Emby.Server.Implementations.HttpServer
}
}
/// <summary>
/// Called when [receive].
/// </summary>
/// <param name="memory">The memory block.</param>
/// <param name="length">The length of the memory block.</param>
private void OnReceiveInternal(Memory<byte> memory, int length)
{
LastActivityDate = DateTime.UtcNow;
if (OnReceive == null)
{
return;
}
var bytes = memory.Slice(0, length).ToArray();
var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
{
OnReceiveInternal(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
}
else
{
OnReceiveInternal(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
private void OnReceiveInternal(string message)
{
LastActivityDate = DateTime.UtcNow;
@@ -193,7 +160,7 @@ namespace Emby.Server.Implementations.HttpServer
var info = new WebSocketMessageInfo
{
MessageType = stub.MessageType,
Data = stub.Data == null ? null : stub.Data.ToString(),
Data = stub.Data?.ToString(),
Connection = this
};

View File

@@ -10,8 +10,8 @@ using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
namespace Emby.Server.Implementations.IO
{
@@ -127,7 +127,6 @@ namespace Emby.Server.Implementations.IO
private IServerConfigurationManager ConfigurationManager { get; set; }
private readonly IFileSystem _fileSystem;
private readonly IEnvironmentInfo _environmentInfo;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
@@ -136,14 +135,12 @@ namespace Emby.Server.Implementations.IO
ILoggerFactory loggerFactory,
ILibraryManager libraryManager,
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
IEnvironmentInfo environmentInfo)
IFileSystem fileSystem)
{
LibraryManager = libraryManager;
Logger = loggerFactory.CreateLogger(GetType().Name);
ConfigurationManager = configurationManager;
_fileSystem = fileSystem;
_environmentInfo = environmentInfo;
}
private bool IsLibraryMonitorEnabled(BaseItem item)
@@ -267,7 +264,7 @@ namespace Emby.Server.Implementations.IO
return;
}
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
if (OperatingSystem.Id != OperatingSystemId.Windows)
{
if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
{
@@ -276,12 +273,6 @@ namespace Emby.Server.Implementations.IO
}
}
if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Android)
{
// causing crashing
return;
}
// Already being watched
if (_fileSystemWatchers.ContainsKey(path))
{

View File

@@ -7,8 +7,8 @@ using System.Text;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
namespace Emby.Server.Implementations.IO
{
@@ -25,22 +25,19 @@ namespace Emby.Server.Implementations.IO
private readonly string _tempPath;
private readonly IEnvironmentInfo _environmentInfo;
private readonly bool _isEnvironmentCaseInsensitive;
public ManagedFileSystem(
ILoggerFactory loggerFactory,
IEnvironmentInfo environmentInfo,
IApplicationPaths applicationPaths)
{
Logger = loggerFactory.CreateLogger("FileSystem");
_supportsAsyncFileStreams = true;
_tempPath = applicationPaths.TempDirectory;
_environmentInfo = environmentInfo;
SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
SetInvalidFileNameChars(OperatingSystem.Id == OperatingSystemId.Windows);
_isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
_isEnvironmentCaseInsensitive = OperatingSystem.Id == OperatingSystemId.Windows;
}
public virtual void AddShortcutHandler(IShortcutHandler handler)
@@ -469,7 +466,7 @@ namespace Emby.Server.Implementations.IO
public virtual void SetHidden(string path, bool isHidden)
{
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
{
return;
}
@@ -493,7 +490,7 @@ namespace Emby.Server.Implementations.IO
public virtual void SetReadOnly(string path, bool isReadOnly)
{
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
{
return;
}
@@ -517,7 +514,7 @@ namespace Emby.Server.Implementations.IO
public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
{
if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
{
return;
}
@@ -711,20 +708,20 @@ namespace Emby.Server.Implementations.IO
return GetFiles(path, null, false, recursive);
}
public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string> extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// On linux and osx the search pattern is case sensitive
// If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1)
{
return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
}
var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
if (extensions != null && extensions.Length > 0)
if (extensions != null && extensions.Count > 0)
{
files = files.Where(i =>
{
@@ -802,7 +799,7 @@ namespace Emby.Server.Implementations.IO
public virtual void SetExecutable(string path)
{
if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
if (OperatingSystem.Id == MediaBrowser.Model.System.OperatingSystemId.Darwin)
{
RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path));
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Buffers;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -8,168 +9,213 @@ namespace Emby.Server.Implementations.IO
{
public class StreamHelper : IStreamHelper
{
private const int StreamCopyToBufferSize = 81920;
public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, Action onStarted, CancellationToken cancellationToken)
{
byte[] buffer = new byte[bufferSize];
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
cancellationToken.ThrowIfCancellationRequested();
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
if (onStarted != null)
int read;
while ((read = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
{
onStarted();
onStarted = null;
cancellationToken.ThrowIfCancellationRequested();
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
if (onStarted != null)
{
onStarted();
onStarted = null;
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task CopyToAsync(Stream source, Stream destination, int bufferSize, int emptyReadLimit, CancellationToken cancellationToken)
{
byte[] buffer = new byte[bufferSize];
if (emptyReadLimit <= 0)
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
if (emptyReadLimit <= 0)
{
int read;
while ((read = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
{
cancellationToken.ThrowIfCancellationRequested();
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
}
return;
}
var eofCount = 0;
while (eofCount < emptyReadLimit)
{
cancellationToken.ThrowIfCancellationRequested();
await destination.WriteAsync(buffer, 0, read).ConfigureAwait(false);
}
var bytesRead = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
return;
if (bytesRead == 0)
{
eofCount++;
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
}
else
{
eofCount = 0;
await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
}
}
}
var eofCount = 0;
while (eofCount < emptyReadLimit)
finally
{
cancellationToken.ThrowIfCancellationRequested();
var bytesRead = source.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
eofCount++;
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
}
else
{
eofCount = 0;
await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
}
ArrayPool<byte>.Shared.Return(buffer);
}
}
const int StreamCopyToBufferSize = 81920;
public async Task<int> CopyToAsync(Stream source, Stream destination, CancellationToken cancellationToken)
{
var array = new byte[StreamCopyToBufferSize];
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
try
{
var bytesToWrite = bytesRead;
int totalBytesRead = 0;
if (bytesToWrite > 0)
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
var bytesToWrite = bytesRead;
totalBytesRead += bytesRead;
if (bytesToWrite > 0)
{
await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
}
}
}
return totalBytesRead;
return totalBytesRead;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task<int> CopyToAsyncWithSyncRead(Stream source, Stream destination, CancellationToken cancellationToken)
{
var array = new byte[StreamCopyToBufferSize];
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
try
{
var bytesToWrite = bytesRead;
int bytesRead;
int totalBytesRead = 0;
if (bytesToWrite > 0)
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) != 0)
{
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
var bytesToWrite = bytesRead;
totalBytesRead += bytesRead;
if (bytesToWrite > 0)
{
await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
}
}
}
return totalBytesRead;
return totalBytesRead;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task CopyToAsyncWithSyncRead(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
{
var array = new byte[StreamCopyToBufferSize];
int bytesRead;
while ((bytesRead = source.Read(array, 0, array.Length)) != 0)
byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
try
{
var bytesToWrite = Math.Min(bytesRead, copyLength);
int bytesRead;
if (bytesToWrite > 0)
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) != 0)
{
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
}
var bytesToWrite = Math.Min(bytesRead, copyLength);
copyLength -= bytesToWrite;
if (bytesToWrite > 0)
{
await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
}
if (copyLength <= 0)
{
break;
copyLength -= bytesToWrite;
if (copyLength <= 0)
{
break;
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task CopyToAsync(Stream source, Stream destination, long copyLength, CancellationToken cancellationToken)
{
var array = new byte[StreamCopyToBufferSize];
int bytesRead;
while ((bytesRead = await source.ReadAsync(array, 0, array.Length, cancellationToken).ConfigureAwait(false)) != 0)
byte[] buffer = ArrayPool<byte>.Shared.Rent(StreamCopyToBufferSize);
try
{
var bytesToWrite = Math.Min(bytesRead, copyLength);
int bytesRead;
if (bytesToWrite > 0)
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(array, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
}
var bytesToWrite = Math.Min(bytesRead, copyLength);
copyLength -= bytesToWrite;
if (bytesToWrite > 0)
{
await destination.WriteAsync(buffer, 0, Convert.ToInt32(bytesToWrite), cancellationToken).ConfigureAwait(false);
}
if (copyLength <= 0)
{
break;
copyLength -= bytesToWrite;
if (copyLength <= 0)
{
break;
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
public async Task CopyUntilCancelled(Stream source, Stream target, int bufferSize, CancellationToken cancellationToken)
{
byte[] buffer = new byte[bufferSize];
while (!cancellationToken.IsCancellationRequested)
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
//var position = fs.Position;
//_logger.LogDebug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
if (bytesRead == 0)
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(100).ConfigureAwait(false);
var bytesRead = await CopyToAsyncInternal(source, target, buffer, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0)
{
await Task.Delay(100).ConfigureAwait(false);
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private static async Task<int> CopyToAsyncInternal(Stream source, Stream destination, byte[] buffer, CancellationToken cancellationToken)

View File

@@ -7,11 +7,6 @@ namespace Emby.Server.Implementations
/// </summary>
string FFmpegPath { get; }
/// <summary>
/// --ffprobe
/// </summary>
string FFprobePath { get; }
/// <summary>
/// --service
/// </summary>

View File

@@ -20,6 +20,9 @@ namespace Emby.Server.Implementations.Images
public abstract class BaseDynamicImageProvider<T> : IHasItemChangeMonitor, IForcedProvider, ICustomMetadataProvider<T>, IHasOrder
where T : BaseItem
{
protected virtual IReadOnlyCollection<ImageType> SupportedImages { get; }
= new ImageType[] { ImageType.Primary };
protected IFileSystem FileSystem { get; private set; }
protected IProviderManager ProviderManager { get; private set; }
protected IApplicationPaths ApplicationPaths { get; private set; }
@@ -33,18 +36,7 @@ namespace Emby.Server.Implementations.Images
ImageProcessor = imageProcessor;
}
protected virtual bool Supports(BaseItem item)
{
return true;
}
public virtual ImageType[] GetSupportedImages(BaseItem item)
{
return new ImageType[]
{
ImageType.Primary
};
}
protected virtual bool Supports(BaseItem _) => true;
public async Task<ItemUpdateType> FetchAsync(T item, MetadataRefreshOptions options, CancellationToken cancellationToken)
{
@@ -54,15 +46,14 @@ namespace Emby.Server.Implementations.Images
}
var updateType = ItemUpdateType.None;
var supportedImages = GetSupportedImages(item);
if (supportedImages.Contains(ImageType.Primary))
if (SupportedImages.Contains(ImageType.Primary))
{
var primaryResult = await FetchAsync(item, ImageType.Primary, options, cancellationToken).ConfigureAwait(false);
updateType = updateType | primaryResult;
}
if (supportedImages.Contains(ImageType.Thumb))
if (SupportedImages.Contains(ImageType.Thumb))
{
var thumbResult = await FetchAsync(item, ImageType.Thumb, options, cancellationToken).ConfigureAwait(false);
updateType = updateType | thumbResult;
@@ -94,7 +85,7 @@ namespace Emby.Server.Implementations.Images
}
protected async Task<ItemUpdateType> FetchToFileInternal(BaseItem item,
List<BaseItem> itemsWithImages,
IReadOnlyList<BaseItem> itemsWithImages,
ImageType imageType,
CancellationToken cancellationToken)
{
@@ -119,9 +110,9 @@ namespace Emby.Server.Implementations.Images
return ItemUpdateType.ImageUpdate;
}
protected abstract List<BaseItem> GetItemsWithImages(BaseItem item);
protected abstract IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item);
protected string CreateThumbCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
protected string CreateThumbCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
{
return CreateCollage(primaryItem, items, outputPath, 640, 360);
}
@@ -132,38 +123,38 @@ namespace Emby.Server.Implementations.Images
.Select(i =>
{
var image = i.GetImageInfo(ImageType.Primary, 0);
if (image != null && image.IsLocalFile)
{
return image.Path;
}
image = i.GetImageInfo(ImageType.Thumb, 0);
if (image != null && image.IsLocalFile)
{
return image.Path;
}
return null;
})
.Where(i => !string.IsNullOrEmpty(i));
}
protected string CreatePosterCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
protected string CreatePosterCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
{
return CreateCollage(primaryItem, items, outputPath, 400, 600);
}
protected string CreateSquareCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath)
protected string CreateSquareCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath)
{
return CreateCollage(primaryItem, items, outputPath, 600, 600);
}
protected string CreateThumbCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
protected string CreateThumbCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath, int width, int height)
{
return CreateCollage(primaryItem, items, outputPath, width, height);
}
private string CreateCollage(BaseItem primaryItem, List<BaseItem> items, string outputPath, int width, int height)
private string CreateCollage(BaseItem primaryItem, IEnumerable<BaseItem> items, string outputPath, int width, int height)
{
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
@@ -192,7 +183,7 @@ namespace Emby.Server.Implementations.Images
public string Name => "Dynamic Image Provider";
protected virtual string CreateImage(BaseItem item,
List<BaseItem> itemsWithImages,
IReadOnlyCollection<BaseItem> itemsWithImages,
string outputPathWithoutExtension,
ImageType imageType,
int imageIndex)
@@ -211,18 +202,15 @@ namespace Emby.Server.Implementations.Images
if (imageType == ImageType.Primary)
{
if (item is UserView)
{
return CreateSquareCollage(item, itemsWithImages, outputPath);
}
if (item is Playlist || item is MusicGenre || item is Genre || item is PhotoAlbum)
if (item is UserView || item is Playlist || item is MusicGenre || item is Genre || item is PhotoAlbum)
{
return CreateSquareCollage(item, itemsWithImages, outputPath);
}
return CreatePosterCollage(item, itemsWithImages, outputPath);
}
throw new ArgumentException("Unexpected image type");
throw new ArgumentException("Unexpected image type", nameof(imageType));
}
protected virtual int MaxImageAgeDays => 7;
@@ -234,13 +222,11 @@ namespace Emby.Server.Implementations.Images
return false;
}
var supportedImages = GetSupportedImages(item);
if (supportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
if (SupportedImages.Contains(ImageType.Primary) && HasChanged(item, ImageType.Primary))
{
return true;
}
if (supportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
if (SupportedImages.Contains(ImageType.Thumb) && HasChanged(item, ImageType.Thumb))
{
return true;
}
@@ -285,7 +271,7 @@ namespace Emby.Server.Implementations.Images
public int Order => 0;
protected string CreateSingleImage(List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
protected string CreateSingleImage(IEnumerable<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType)
{
var image = itemsWithImages
.Where(i => i.HasImage(imageType) && i.GetImageInfo(imageType, 0).IsLocalFile && Path.HasExtension(i.GetImagePath(imageType)))

View File

@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Controller.Authentication;
@@ -18,20 +19,64 @@ namespace Emby.Server.Implementations.Library
public string Name => "Default";
public bool IsEnabled => true;
// This is dumb and an artifact of the backwards way auth providers were designed.
// This version of authenticate was never meant to be called, but needs to be here for interface compat
// Only the providers that don't provide local user support use this
public Task<ProviderAuthenticationResult> Authenticate(string username, string password)
{
throw new NotImplementedException();
}
// This is the verson that we need to use for local users. Because reasons.
public Task<ProviderAuthenticationResult> Authenticate(string username, string password, User resolvedUser)
{
bool success = false;
if (resolvedUser == null)
{
throw new Exception("Invalid username or password");
}
var success = string.Equals(GetPasswordHash(resolvedUser), GetHashedString(resolvedUser, password), StringComparison.OrdinalIgnoreCase);
// As long as jellyfin supports passwordless users, we need this little block here to accomodate
if (IsPasswordEmpty(resolvedUser, password))
{
return Task.FromResult(new ProviderAuthenticationResult
{
Username = username
});
}
ConvertPasswordFormat(resolvedUser);
byte[] passwordbytes = Encoding.UTF8.GetBytes(password);
PasswordHash readyHash = new PasswordHash(resolvedUser.Password);
byte[] calculatedHash;
string calculatedHashString;
if (_cryptographyProvider.GetSupportedHashMethods().Contains(readyHash.Id) || _cryptographyProvider.DefaultHashMethod == readyHash.Id)
{
if (string.IsNullOrEmpty(readyHash.Salt))
{
calculatedHash = _cryptographyProvider.ComputeHash(readyHash.Id, passwordbytes);
calculatedHashString = BitConverter.ToString(calculatedHash).Replace("-", string.Empty);
}
else
{
calculatedHash = _cryptographyProvider.ComputeHash(readyHash.Id, passwordbytes, readyHash.SaltBytes);
calculatedHashString = BitConverter.ToString(calculatedHash).Replace("-", string.Empty);
}
if (calculatedHashString == readyHash.Hash)
{
success = true;
// throw new Exception("Invalid username or password");
}
}
else
{
throw new Exception(string.Format($"Requested crypto method not available in provider: {readyHash.Id}"));
}
// var success = string.Equals(GetPasswordHash(resolvedUser), GetHashedString(resolvedUser, password), StringComparison.OrdinalIgnoreCase);
if (!success)
{
@@ -44,46 +89,86 @@ namespace Emby.Server.Implementations.Library
});
}
// This allows us to move passwords forward to the newformat without breaking. They are still insecure, unsalted, and dumb before a password change
// but at least they are in the new format.
private void ConvertPasswordFormat(User user)
{
if (string.IsNullOrEmpty(user.Password))
{
return;
}
if (!user.Password.Contains("$"))
{
string hash = user.Password;
user.Password = string.Format("$SHA1${0}", hash);
}
if (user.EasyPassword != null && !user.EasyPassword.Contains("$"))
{
string hash = user.EasyPassword;
user.EasyPassword = string.Format("$SHA1${0}", hash);
}
}
public Task<bool> HasPassword(User user)
{
var hasConfiguredPassword = !IsPasswordEmpty(user, GetPasswordHash(user));
return Task.FromResult(hasConfiguredPassword);
}
private bool IsPasswordEmpty(User user, string passwordHash)
private bool IsPasswordEmpty(User user, string password)
{
return string.Equals(passwordHash, GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
return (string.IsNullOrEmpty(user.Password) && string.IsNullOrEmpty(password));
}
public Task ChangePassword(User user, string newPassword)
{
string newPasswordHash = null;
if (newPassword != null)
ConvertPasswordFormat(user);
// This is needed to support changing a no password user to a password user
if (string.IsNullOrEmpty(user.Password))
{
newPasswordHash = GetHashedString(user, newPassword);
PasswordHash newPasswordHash = new PasswordHash(_cryptographyProvider);
newPasswordHash.SaltBytes = _cryptographyProvider.GenerateSalt();
newPasswordHash.Salt = PasswordHash.ConvertToByteString(newPasswordHash.SaltBytes);
newPasswordHash.Id = _cryptographyProvider.DefaultHashMethod;
newPasswordHash.Hash = GetHashedStringChangeAuth(newPassword, newPasswordHash);
user.Password = newPasswordHash.ToString();
return Task.CompletedTask;
}
if (string.IsNullOrWhiteSpace(newPasswordHash))
PasswordHash passwordHash = new PasswordHash(user.Password);
if (passwordHash.Id == "SHA1" && string.IsNullOrEmpty(passwordHash.Salt))
{
throw new ArgumentNullException(nameof(newPasswordHash));
passwordHash.SaltBytes = _cryptographyProvider.GenerateSalt();
passwordHash.Salt = PasswordHash.ConvertToByteString(passwordHash.SaltBytes);
passwordHash.Id = _cryptographyProvider.DefaultHashMethod;
passwordHash.Hash = GetHashedStringChangeAuth(newPassword, passwordHash);
}
else if (newPassword != null)
{
passwordHash.Hash = GetHashedString(user, newPassword);
}
user.Password = newPasswordHash;
if (string.IsNullOrWhiteSpace(passwordHash.Hash))
{
throw new ArgumentNullException(nameof(passwordHash.Hash));
}
user.Password = passwordHash.ToString();
return Task.CompletedTask;
}
public string GetPasswordHash(User user)
{
return string.IsNullOrEmpty(user.Password)
? GetEmptyHashedString(user)
: user.Password;
return user.Password;
}
public string GetEmptyHashedString(User user)
public string GetHashedStringChangeAuth(string newPassword, PasswordHash passwordHash)
{
return GetHashedString(user, string.Empty);
passwordHash.HashBytes = Encoding.UTF8.GetBytes(newPassword);
return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash));
}
/// <summary>
@@ -91,14 +176,28 @@ namespace Emby.Server.Implementations.Library
/// </summary>
public string GetHashedString(User user, string str)
{
var salt = user.Salt;
if (salt != null)
PasswordHash passwordHash;
if (string.IsNullOrEmpty(user.Password))
{
// return BCrypt.HashPassword(str, salt);
passwordHash = new PasswordHash(_cryptographyProvider);
}
else
{
ConvertPasswordFormat(user);
passwordHash = new PasswordHash(user.Password);
}
// legacy
return BitConverter.ToString(_cryptographyProvider.ComputeSHA1(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
if (passwordHash.SaltBytes != null)
{
// the password is modern format with PBKDF and we should take advantage of that
passwordHash.HashBytes = Encoding.UTF8.GetBytes(str);
return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash));
}
else
{
// the password has no salt and should be called with the older method for safety
return PasswordHash.ConvertToByteString(_cryptographyProvider.ComputeHash(passwordHash.Id, Encoding.UTF8.GetBytes(str)));
}
}
}
}

View File

@@ -58,22 +58,23 @@ namespace Emby.Server.Implementations.Library
private ILibraryPostScanTask[] PostscanTasks { get; set; }
/// <summary>
/// Gets the intro providers.
/// Gets or sets the intro providers.
/// </summary>
/// <value>The intro providers.</value>
private IIntroProvider[] IntroProviders { get; set; }
/// <summary>
/// Gets the list of entity resolution ignore rules
/// Gets or sets the list of entity resolution ignore rules
/// </summary>
/// <value>The entity resolution ignore rules.</value>
private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
/// <summary>
/// Gets the list of currently registered entity resolvers
/// Gets or sets the list of currently registered entity resolvers
/// </summary>
/// <value>The entity resolvers enumerable.</value>
private IItemResolver[] EntityResolvers { get; set; }
private IMultiItemResolver[] MultiItemResolvers { get; set; }
/// <summary>
@@ -83,7 +84,7 @@ namespace Emby.Server.Implementations.Library
private IBaseItemComparer[] Comparers { get; set; }
/// <summary>
/// Gets the active item repository
/// Gets or sets the active item repository
/// </summary>
/// <value>The item repository.</value>
public IItemRepository ItemRepository { get; set; }
@@ -133,12 +134,14 @@ namespace Emby.Server.Implementations.Library
private readonly Func<IProviderManager> _providerManagerFactory;
private readonly Func<IUserViewManager> _userviewManager;
public bool IsScanRunning { get; private set; }
private IServerApplicationHost _appHost;
/// <summary>
/// The _library items cache
/// </summary>
private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
/// <summary>
/// Gets the library items cache.
/// </summary>
@@ -150,7 +153,8 @@ namespace Emby.Server.Implementations.Library
/// <summary>
/// Initializes a new instance of the <see cref="LibraryManager" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="appHost">The application host</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="taskManager">The task manager.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="configurationManager">The configuration manager.</param>
@@ -167,6 +171,7 @@ namespace Emby.Server.Implementations.Library
Func<IProviderManager> providerManagerFactory,
Func<IUserViewManager> userviewManager)
{
_appHost = appHost;
_logger = loggerFactory.CreateLogger(nameof(LibraryManager));
_taskManager = taskManager;
_userManager = userManager;
@@ -176,7 +181,7 @@ namespace Emby.Server.Implementations.Library
_fileSystem = fileSystem;
_providerManagerFactory = providerManagerFactory;
_userviewManager = userviewManager;
_appHost = appHost;
_libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
@@ -191,8 +196,9 @@ namespace Emby.Server.Implementations.Library
/// <param name="resolvers">The resolvers.</param>
/// <param name="introProviders">The intro providers.</param>
/// <param name="itemComparers">The item comparers.</param>
/// <param name="postscanTasks">The postscan tasks.</param>
public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
/// <param name="postscanTasks">The post scan tasks.</param>
public void AddParts(
IEnumerable<IResolverIgnoreRule> rules,
IEnumerable<IItemResolver> resolvers,
IEnumerable<IIntroProvider> introProviders,
IEnumerable<IBaseItemComparer> itemComparers,
@@ -203,24 +209,19 @@ namespace Emby.Server.Implementations.Library
MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
IntroProviders = introProviders.ToArray();
Comparers = itemComparers.ToArray();
PostscanTasks = postscanTasks.OrderBy(i =>
{
var hasOrder = i as IHasOrder;
return hasOrder == null ? 0 : hasOrder.Order;
}).ToArray();
PostscanTasks = postscanTasks.ToArray();
}
/// <summary>
/// The _root folder
/// </summary>
private volatile AggregateFolder _rootFolder;
/// <summary>
/// The _root folder sync lock
/// </summary>
private readonly object _rootFolderSyncLock = new object();
/// <summary>
/// Gets the root folder.
/// </summary>
@@ -239,11 +240,13 @@ namespace Emby.Server.Implementations.Library
}
}
}
return _rootFolder;
}
}
private bool _wizardCompleted;
/// <summary>
/// Records the configuration values.
/// </summary>
@@ -258,7 +261,7 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
void ConfigurationUpdated(object sender, EventArgs e)
private void ConfigurationUpdated(object sender, EventArgs e)
{
var config = ConfigurationManager.Configuration;
@@ -278,6 +281,7 @@ namespace Emby.Server.Implementations.Library
{
throw new ArgumentNullException(nameof(item));
}
if (item is IItemByName)
{
if (!(item is MusicArtist))
@@ -285,18 +289,7 @@ namespace Emby.Server.Implementations.Library
return;
}
}
else if (item.IsFolder)
{
//if (!(item is ICollectionFolder) && !(item is UserView) && !(item is Channel) && !(item is AggregateFolder))
//{
// if (item.SourceType != SourceType.Library)
// {
// return;
// }
//}
}
else
else if (!item.IsFolder)
{
if (!(item is Video) && !(item is LiveTvChannel))
{
@@ -345,12 +338,14 @@ namespace Emby.Server.Implementations.Library
// channel no longer installed
}
}
options.DeleteFileLocation = false;
}
if (item is LiveTvProgram)
{
_logger.LogDebug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
_logger.LogDebug(
"Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
item.GetType().Name,
item.Name ?? "Unknown name",
item.Path ?? string.Empty,
@@ -358,7 +353,8 @@ namespace Emby.Server.Implementations.Library
}
else
{
_logger.LogInformation("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
_logger.LogInformation(
"Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
item.GetType().Name,
item.Name ?? "Unknown name",
item.Path ?? string.Empty,
@@ -371,19 +367,20 @@ namespace Emby.Server.Implementations.Library
foreach (var metadataPath in GetMetadataPaths(item, children))
{
_logger.LogDebug("Deleting path {0}", metadataPath);
if (!Directory.Exists(metadataPath))
{
continue;
}
_logger.LogDebug("Deleting path {MetadataPath}", metadataPath);
try
{
Directory.Delete(metadataPath, true);
}
catch (IOException)
{
}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting {metadataPath}", metadataPath);
_logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
}
}
@@ -497,12 +494,13 @@ namespace Emby.Server.Implementations.Library
{
throw new ArgumentNullException(nameof(key));
}
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath))
if (key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath, StringComparison.Ordinal))
{
// Try to normalize paths located underneath program-data in an attempt to make them more portable
key = key.Substring(ConfigurationManager.ApplicationPaths.ProgramDataPath.Length)
@@ -520,13 +518,11 @@ namespace Emby.Server.Implementations.Library
return key.GetMD5();
}
public BaseItem ResolvePath(FileSystemMetadata fileInfo,
Folder parent = null)
{
return ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), null, parent);
}
public BaseItem ResolvePath(FileSystemMetadata fileInfo, Folder parent = null)
=> ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), null, parent);
private BaseItem ResolvePath(FileSystemMetadata fileInfo,
private BaseItem ResolvePath(
FileSystemMetadata fileInfo,
IDirectoryService directoryService,
IItemResolver[] resolvers,
Folder parent = null,
@@ -581,7 +577,7 @@ namespace Emby.Server.Implementations.Library
{
_logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
files = new FileSystemMetadata[] { };
files = Array.Empty<FileSystemMetadata>();
}
else
{
@@ -609,13 +605,7 @@ namespace Emby.Server.Implementations.Library
}
public bool IgnoreFile(FileSystemMetadata file, BaseItem parent)
{
if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent)))
{
return true;
}
return false;
}
=> EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
{
@@ -655,7 +645,8 @@ namespace Emby.Server.Implementations.Library
return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
}
public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files,
public IEnumerable<BaseItem> ResolvePaths(
IEnumerable<FileSystemMetadata> files,
IDirectoryService directoryService,
Folder parent,
LibraryOptions libraryOptions,
@@ -681,6 +672,7 @@ namespace Emby.Server.Implementations.Library
{
ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService);
}
items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions));
return items;
}
@@ -690,7 +682,8 @@ namespace Emby.Server.Implementations.Library
return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
}
private IEnumerable<BaseItem> ResolveFileList(IEnumerable<FileSystemMetadata> fileList,
private IEnumerable<BaseItem> ResolveFileList(
IEnumerable<FileSystemMetadata> fileList,
IDirectoryService directoryService,
Folder parent,
string collectionType,
@@ -775,6 +768,7 @@ namespace Emby.Server.Implementations.Library
private volatile UserRootFolder _userRootFolder;
private readonly object _syncLock = new object();
public Folder GetUserRootFolder()
{
if (_userRootFolder == null)
@@ -819,8 +813,6 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(path));
}
//_logger.LogInformation("FindByPath {0}", path);
var query = new InternalItemsQuery
{
Path = path,
@@ -894,7 +886,6 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="value">The value.</param>
/// <returns>Task{Year}.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public Year GetYear(int value)
{
if (value <= 0)
@@ -1036,20 +1027,25 @@ namespace Emby.Server.Implementations.Library
private async Task ValidateTopLibraryFolders(CancellationToken cancellationToken)
{
var rootChildren = RootFolder.Children.ToList();
rootChildren = GetUserRootFolder().Children.ToList();
await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
// Start by just validating the children of the root, but go no further
await RootFolder.ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false);
await RootFolder.ValidateChildren(
new SimpleProgress<double>(),
cancellationToken,
new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)),
recursive: false).ConfigureAwait(false);
await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
await GetUserRootFolder().ValidateChildren(new SimpleProgress<double>(), cancellationToken, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), recursive: false).ConfigureAwait(false);
await GetUserRootFolder().ValidateChildren(
new SimpleProgress<double>(),
cancellationToken,
new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)),
recursive: false).ConfigureAwait(false);
// Quickly scan CollectionFolders for changes
foreach (var folder in GetUserRootFolder().Children.OfType<Folder>().ToList())
foreach (var folder in GetUserRootFolder().Children.OfType<Folder>())
{
await folder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
}
@@ -1213,7 +1209,7 @@ namespace Emby.Server.Implementations.Library
private string GetCollectionType(string path)
{
return _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false)
.Select(i => Path.GetFileNameWithoutExtension(i))
.Select(Path.GetFileNameWithoutExtension)
.FirstOrDefault(i => !string.IsNullOrEmpty(i));
}
@@ -1227,7 +1223,7 @@ namespace Emby.Server.Implementations.Library
{
if (id == Guid.Empty)
{
throw new ArgumentException(nameof(id), "Guid can't be empty");
throw new ArgumentException("Guid can't be empty", nameof(id));
}
if (LibraryItemsCache.TryGetValue(id, out BaseItem item))
@@ -1395,17 +1391,7 @@ namespace Emby.Server.Implementations.Library
var parents = query.AncestorIds.Select(i => GetItemById(i)).ToList();
if (parents.All(i =>
{
if (i is ICollectionFolder || i is UserView)
{
return true;
}
//_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
return false;
}))
if (parents.All(i => i is ICollectionFolder || i is UserView))
{
// Optimize by querying against top level views
query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
@@ -1461,17 +1447,7 @@ namespace Emby.Server.Implementations.Library
private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem> parents)
{
if (parents.All(i =>
{
if (i is ICollectionFolder || i is UserView)
{
return true;
}
//_logger.LogDebug("Query requires ancestor query due to type: " + i.GetType().Name);
return false;
}))
if (parents.All(i => i is ICollectionFolder || i is UserView))
{
// Optimize by querying against top level views
query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
@@ -1520,11 +1496,9 @@ namespace Emby.Server.Implementations.Library
private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User user)
{
var view = item as UserView;
if (view != null)
if (item is UserView view)
{
if (string.Equals(view.ViewType, CollectionType.LiveTv))
if (string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.Ordinal))
{
return new[] { view.Id };
}
@@ -1537,8 +1511,10 @@ namespace Emby.Server.Implementations.Library
{
return GetTopParentIdsForQuery(displayParent, user);
}
return Array.Empty<Guid>();
}
if (!view.ParentId.Equals(Guid.Empty))
{
var displayParent = GetItemById(view.ParentId);
@@ -1546,6 +1522,7 @@ namespace Emby.Server.Implementations.Library
{
return GetTopParentIdsForQuery(displayParent, user);
}
return Array.Empty<Guid>();
}
@@ -1559,11 +1536,11 @@ namespace Emby.Server.Implementations.Library
.Where(i => user.IsFolderGrouped(i.Id))
.SelectMany(i => GetTopParentIdsForQuery(i, user));
}
return Array.Empty<Guid>();
}
var collectionFolder = item as CollectionFolder;
if (collectionFolder != null)
if (item is CollectionFolder collectionFolder)
{
return collectionFolder.PhysicalFolderIds;
}
@@ -1573,6 +1550,7 @@ namespace Emby.Server.Implementations.Library
{
return new[] { topParent.Id };
}
return Array.Empty<Guid>();
}
@@ -1769,19 +1747,16 @@ namespace Emby.Server.Implementations.Library
{
var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
if (comparer != null)
// If it requires a user, create a new one, and assign the user
if (comparer is IUserBaseItemComparer)
{
// If it requires a user, create a new one, and assign the user
if (comparer is IUserBaseItemComparer)
{
var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
userComparer.User = user;
userComparer.UserManager = _userManager;
userComparer.UserDataRepository = _userDataRepository;
userComparer.User = user;
userComparer.UserManager = _userManager;
userComparer.UserDataRepository = _userDataRepository;
return userComparer;
}
return userComparer;
}
return comparer;
@@ -1792,7 +1767,6 @@ namespace Emby.Server.Implementations.Library
/// </summary>
/// <param name="item">The item.</param>
/// <param name="parent">The parent item.</param>
/// <returns>Task.</returns>
public void CreateItem(BaseItem item, BaseItem parent)
{
CreateItems(new[] { item }, parent, CancellationToken.None);
@@ -1802,20 +1776,23 @@ namespace Emby.Server.Implementations.Library
/// Creates the items.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="parent">The parent item</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public void CreateItems(IEnumerable<BaseItem> items, BaseItem parent, CancellationToken cancellationToken)
{
ItemRepository.SaveItems(items, cancellationToken);
// Don't iterate multiple times
var itemsList = items.ToList();
foreach (var item in items)
ItemRepository.SaveItems(itemsList, cancellationToken);
foreach (var item in itemsList)
{
RegisterItem(item);
}
if (ItemAdded != null)
{
foreach (var item in items)
foreach (var item in itemsList)
{
// With the live tv guide this just creates too much noise
if (item.SourceType != SourceType.Library)
@@ -1825,11 +1802,13 @@ namespace Emby.Server.Implementations.Library
try
{
ItemAdded(this, new ItemChangeEventArgs
{
Item = item,
Parent = parent ?? item.GetParent()
});
ItemAdded(
this,
new ItemChangeEventArgs
{
Item = item,
Parent = parent ?? item.GetParent()
});
}
catch (Exception ex)
{
@@ -1851,7 +1830,10 @@ namespace Emby.Server.Implementations.Library
/// </summary>
public void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
{
foreach (var item in items)
// Don't iterate multiple times
var itemsList = items.ToList();
foreach (var item in itemsList)
{
if (item.IsFileProtocol)
{
@@ -1863,14 +1845,11 @@ namespace Emby.Server.Implementations.Library
RegisterItem(item);
}
//var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
//_logger.LogDebug("Saving {0} to database.", logName);
ItemRepository.SaveItems(items, cancellationToken);
ItemRepository.SaveItems(itemsList, cancellationToken);
if (ItemUpdated != null)
{
foreach (var item in items)
foreach (var item in itemsList)
{
// With the live tv guide this just creates too much noise
if (item.SourceType != SourceType.Library)
@@ -1880,12 +1859,14 @@ namespace Emby.Server.Implementations.Library
try
{
ItemUpdated(this, new ItemChangeEventArgs
{
Item = item,
Parent = parent,
UpdateReason = updateReason
});
ItemUpdated(
this,
new ItemChangeEventArgs
{
Item = item,
Parent = parent,
UpdateReason = updateReason
});
}
catch (Exception ex)
{
@@ -1899,9 +1880,9 @@ namespace Emby.Server.Implementations.Library
/// Updates the item.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="parent">The parent item.</param>
/// <param name="updateReason">The update reason.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
{
UpdateItems(new [] { item }, parent, updateReason, cancellationToken);
@@ -1911,17 +1892,20 @@ namespace Emby.Server.Implementations.Library
/// Reports the item removed.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="parent">The parent item.</param>
public void ReportItemRemoved(BaseItem item, BaseItem parent)
{
if (ItemRemoved != null)
{
try
{
ItemRemoved(this, new ItemChangeEventArgs
{
Item = item,
Parent = parent
});
ItemRemoved(
this,
new ItemChangeEventArgs
{
Item = item,
Parent = parent
});
}
catch (Exception ex)
{
@@ -2047,8 +2031,7 @@ namespace Emby.Server.Implementations.Library
public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
{
var collectionFolder = item as ICollectionFolder;
if (collectionFolder != null)
if (item is ICollectionFolder collectionFolder)
{
return collectionFolder.CollectionType;
}
@@ -2058,13 +2041,11 @@ namespace Emby.Server.Implementations.Library
private string GetContentTypeOverride(string path, bool inherit)
{
var nameValuePair = ConfigurationManager.Configuration.ContentTypes.FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path) || (inherit && !string.IsNullOrEmpty(i.Name) && _fileSystem.ContainsSubPath(i.Name, path)));
if (nameValuePair != null)
{
return nameValuePair.Value;
}
return null;
var nameValuePair = ConfigurationManager.Configuration.ContentTypes
.FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
|| (inherit && !string.IsNullOrEmpty(i.Name)
&& _fileSystem.ContainsSubPath(i.Name, path)));
return nameValuePair?.Value;
}
private string GetTopFolderContentType(BaseItem item)
@@ -2081,6 +2062,7 @@ namespace Emby.Server.Implementations.Library
{
break;
}
item = parent;
}
@@ -2092,9 +2074,9 @@ namespace Emby.Server.Implementations.Library
}
private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
//private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromMinutes(1);
public UserView GetNamedView(User user,
public UserView GetNamedView(
User user,
string name,
string viewType,
string sortName)
@@ -2102,13 +2084,15 @@ namespace Emby.Server.Implementations.Library
return GetNamedView(user, name, Guid.Empty, viewType, sortName);
}
public UserView GetNamedView(string name,
public UserView GetNamedView(
string name,
string viewType,
string sortName)
{
var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath,
"views",
_fileSystem.GetValidFilename(viewType));
var path = Path.Combine(
ConfigurationManager.ApplicationPaths.InternalMetadataPath,
"views",
_fileSystem.GetValidFilename(viewType));
var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
@@ -2144,7 +2128,8 @@ namespace Emby.Server.Implementations.Library
return item;
}
public UserView GetNamedView(User user,
public UserView GetNamedView(
User user,
string name,
Guid parentId,
string viewType,
@@ -2173,10 +2158,10 @@ namespace Emby.Server.Implementations.Library
Name = name,
ViewType = viewType,
ForcedSortName = sortName,
UserId = user.Id
UserId = user.Id,
DisplayParentId = parentId
};
item.DisplayParentId = parentId;
CreateItem(item, null);
@@ -2193,20 +2178,24 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
_providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
_providerManagerFactory().QueueRefresh(
item.Id,
new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
}, RefreshPriority.Normal);
},
RefreshPriority.Normal);
}
return item;
}
public UserView GetShadowView(BaseItem parent,
string viewType,
string sortName)
public UserView GetShadowView(
BaseItem parent,
string viewType,
string sortName)
{
if (parent == null)
{
@@ -2257,18 +2246,21 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
_providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
}, RefreshPriority.Normal);
_providerManagerFactory().QueueRefresh(
item.Id,
new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
},
RefreshPriority.Normal);
}
return item;
}
public UserView GetNamedView(string name,
public UserView GetNamedView(
string name,
Guid parentId,
string viewType,
string sortName,
@@ -2331,17 +2323,21 @@ namespace Emby.Server.Implementations.Library
if (refresh)
{
_providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
}, RefreshPriority.Normal);
_providerManagerFactory().QueueRefresh(
item.Id,
new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem))
{
// Need to force save to increment DateLastSaved
ForceSave = true
},
RefreshPriority.Normal);
}
return item;
}
public void AddExternalSubtitleStreams(List<MediaStream> streams,
public void AddExternalSubtitleStreams(
List<MediaStream> streams,
string videoPath,
string[] files)
{
@@ -2445,6 +2441,7 @@ namespace Emby.Server.Implementations.Library
{
changed = true;
}
episode.IndexNumber = episodeInfo.EpisodeNumber;
}
@@ -2454,6 +2451,7 @@ namespace Emby.Server.Implementations.Library
{
changed = true;
}
episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
}
@@ -2463,6 +2461,7 @@ namespace Emby.Server.Implementations.Library
{
changed = true;
}
episode.ParentIndexNumber = episodeInfo.SeasonNumber;
}
}
@@ -2492,6 +2491,7 @@ namespace Emby.Server.Implementations.Library
private NamingOptions _namingOptions;
private string[] _videoFileExtensions;
private NamingOptions GetNamingOptionsInternal()
{
if (_namingOptions == null)
@@ -2688,7 +2688,7 @@ namespace Emby.Server.Implementations.Library
var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
var changed = false;
if (!string.Equals(newPath, path))
if (!string.Equals(newPath, path, StringComparison.Ordinal))
{
if (to.IndexOf('/') != -1)
{
@@ -2812,6 +2812,7 @@ namespace Emby.Server.Implementations.Library
{
continue;
}
throw;
}
}
@@ -2916,6 +2917,7 @@ namespace Emby.Server.Implementations.Library
}
private const string ShortcutFileExtension = ".mblink";
public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
{
AddMediaPathInternal(virtualFolderName, pathInfo, true);
@@ -2932,7 +2934,7 @@ namespace Emby.Server.Implementations.Library
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
throw new ArgumentException(nameof(path));
}
if (!Directory.Exists(path))

View File

@@ -4,6 +4,7 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Events;
@@ -213,22 +214,17 @@ namespace Emby.Server.Implementations.Library
}
}
public bool IsValidUsername(string username)
public static bool IsValidUsername(string username)
{
// Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
foreach (var currentChar in username)
{
if (!IsValidUsernameCharacter(currentChar))
{
return false;
}
}
return true;
//This is some regex that matches only on unicode "word" characters, as well as -, _ and @
//In theory this will cut out most if not all 'control' characters which should help minimize any weirdness
// Usernames can contain letters (a-z + whatever else unicode is cool with), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)
return Regex.IsMatch(username, "^[\\w-'._@]*$");
}
private static bool IsValidUsernameCharacter(char i)
{
return !char.Equals(i, '<') && !char.Equals(i, '>');
return IsValidUsername(i.ToString());
}
public string MakeValidUsername(string username)
@@ -475,15 +471,10 @@ namespace Emby.Server.Implementations.Library
private string GetLocalPasswordHash(User user)
{
return string.IsNullOrEmpty(user.EasyPassword)
? _defaultAuthenticationProvider.GetEmptyHashedString(user)
? null
: user.EasyPassword;
}
private bool IsPasswordEmpty(User user, string passwordHash)
{
return string.Equals(passwordHash, _defaultAuthenticationProvider.GetEmptyHashedString(user), StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Loads the users from the repository
/// </summary>
@@ -526,14 +517,14 @@ namespace Emby.Server.Implementations.Library
throw new ArgumentNullException(nameof(user));
}
var hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
var hasConfiguredEasyPassword = !IsPasswordEmpty(user, GetLocalPasswordHash(user));
bool hasConfiguredPassword = GetAuthenticationProvider(user).HasPassword(user).Result;
bool hasConfiguredEasyPassword = string.IsNullOrEmpty(GetLocalPasswordHash(user));
var hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
bool hasPassword = user.Configuration.EnableLocalPassword && !string.IsNullOrEmpty(remoteEndPoint) && _networkManager.IsInLocalNetwork(remoteEndPoint) ?
hasConfiguredEasyPassword :
hasConfiguredPassword;
var dto = new UserDto
UserDto dto = new UserDto
{
Id = user.Id,
Name = user.Name,
@@ -552,7 +543,7 @@ namespace Emby.Server.Implementations.Library
dto.EnableAutoLogin = true;
}
var image = user.GetImageInfo(ImageType.Primary, 0);
ItemImageInfo image = user.GetImageInfo(ImageType.Primary, 0);
if (image != null)
{
@@ -688,7 +679,7 @@ namespace Emby.Server.Implementations.Library
if (!IsValidUsername(name))
{
throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
throw new ArgumentException("Usernames can contain unicode symbols, numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)");
}
if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))

View File

@@ -33,7 +33,6 @@ using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Reflection;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
@@ -58,7 +57,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
private readonly IProviderManager _providerManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly IProcessFactory _processFactory;
private readonly IAssemblyInfo _assemblyInfo;
private IMediaSourceManager _mediaSourceManager;
public static EmbyTV Current;
@@ -74,7 +72,6 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
public EmbyTV(IServerApplicationHost appHost,
IStreamHelper streamHelper,
IMediaSourceManager mediaSourceManager,
IAssemblyInfo assemblyInfo,
ILogger logger,
IJsonSerializer jsonSerializer,
IHttpClient httpClient,
@@ -101,12 +98,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
_processFactory = processFactory;
_liveTvManager = (LiveTvManager)liveTvManager;
_jsonSerializer = jsonSerializer;
_assemblyInfo = assemblyInfo;
_mediaSourceManager = mediaSourceManager;
_streamHelper = streamHelper;
_seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
_timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger);
_seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers.json"));
_timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers.json"), _logger);
_timerProvider.TimerFired += _timerProvider_TimerFired;
_config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;

View File

@@ -2,7 +2,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
@@ -32,32 +31,28 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
{
if (_items == null)
{
if (!File.Exists(_dataPath))
{
return new List<T>();
}
Logger.LogInformation("Loading live tv data from {0}", _dataPath);
_items = GetItemsFromFile(_dataPath);
}
return _items.ToList();
}
}
private List<T> GetItemsFromFile(string path)
{
var jsonFile = path + ".json";
if (!File.Exists(jsonFile))
{
return new List<T>();
}
try
{
return _jsonSerializer.DeserializeFromFile<List<T>>(jsonFile) ?? new List<T>();
}
catch (IOException)
{
return _jsonSerializer.DeserializeFromFile<List<T>>(path);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error deserializing {jsonFile}", jsonFile);
Logger.LogError(ex, "Error deserializing {Path}", path);
}
return new List<T>();
@@ -70,12 +65,11 @@ namespace Emby.Server.Implementations.LiveTv.EmbyTV
throw new ArgumentNullException(nameof(newList));
}
var file = _dataPath + ".json";
Directory.CreateDirectory(Path.GetDirectoryName(file));
Directory.CreateDirectory(Path.GetDirectoryName(_dataPath));
lock (_fileDataLock)
{
_jsonSerializer.SerializeToFile(newList, file);
_jsonSerializer.SerializeToFile(newList, _dataPath);
_items = newList;
}
}

View File

@@ -17,6 +17,7 @@ using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.LiveTv.Listings
{
@@ -638,7 +639,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
#if NETSTANDARD2_0
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
options.RequestHeaders["Accept-Encoding"] = "deflate";
options.RequestHeaders[HeaderNames.AcceptEncoding] = "deflate";
}
#endif
@@ -676,7 +677,7 @@ namespace Emby.Server.Implementations.LiveTv.Listings
#if NETSTANDARD2_0
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
options.RequestHeaders["Accept-Encoding"] = "deflate";
options.RequestHeaders[HeaderNames.AcceptEncoding] = "deflate";
}
#endif

View File

@@ -151,7 +151,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
});
}
private static int RtpHeaderBytes = 12;
private const int RtpHeaderBytes = 12;
private async Task CopyTo(MediaBrowser.Model.Net.ISocket udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
{
var bufferSize = 81920;

View File

@@ -22,7 +22,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
public string OriginalStreamId { get; set; }
public bool EnableStreamSharing { get; set; }
public string UniqueId { get; private set; }
public string UniqueId { get; }
protected readonly IFileSystem FileSystem;
protected readonly IServerApplicationPaths AppPaths;
@@ -31,12 +31,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
protected readonly ILogger Logger;
protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
public string TunerHostId { get; private set; }
public string TunerHostId { get; }
public DateTime DateOpened { get; protected set; }
public Func<Task> OnClose { get; set; }
public LiveStream(MediaSourceInfo mediaSource, TunerHostInfo tuner, IFileSystem fileSystem, ILogger logger, IServerApplicationPaths appPaths)
{
OriginalMediaSource = mediaSource;
@@ -76,26 +74,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
LiveStreamCancellationTokenSource.Cancel();
if (OnClose != null)
{
return CloseWithExternalFn();
}
return Task.CompletedTask;
}
private async Task CloseWithExternalFn()
{
try
{
await OnClose().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error closing live stream");
}
}
protected Stream GetInputStream(string path, bool allowAsyncFileRead)
{
var fileOpenOptions = FileOpenOptions.SequentialScan;
@@ -113,27 +94,26 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
return DeleteTempFiles(GetStreamFilePaths());
}
protected async Task DeleteTempFiles(List<string> paths, int retryCount = 0)
protected async Task DeleteTempFiles(IEnumerable<string> paths, int retryCount = 0)
{
if (retryCount == 0)
{
Logger.LogInformation("Deleting temp files {0}", string.Join(", ", paths.ToArray()));
Logger.LogInformation("Deleting temp files {0}", paths);
}
var failedFiles = new List<string>();
foreach (var path in paths)
{
if (!File.Exists(path))
{
continue;
}
try
{
FileSystem.DeleteFile(path);
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
Logger.LogError(ex, "Error deleting file {path}", path);
@@ -157,8 +137,8 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
var allowAsync = false;
// use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
// use non-async filestream on windows along with read due to https://github.com/dotnet/corefx/issues/6039
var allowAsync = Environment.OSVersion.Platform != PlatformID.Win32NT;
bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
@@ -181,28 +161,24 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
Logger.LogInformation("Live Stream ended.");
}
private Tuple<string, bool> GetNextFile(string currentFile)
private (string file, bool isLastFile) GetNextFile(string currentFile)
{
var files = GetStreamFilePaths();
//logger.LogInformation("Live stream files: {0}", string.Join(", ", files.ToArray()));
if (string.IsNullOrEmpty(currentFile))
{
return new Tuple<string, bool>(files.Last(), true);
return (files.Last(), true);
}
var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
var isLastFile = nextIndex == files.Count - 1;
return new Tuple<string, bool>(files.ElementAtOrDefault(nextIndex), isLastFile);
return (files.ElementAtOrDefault(nextIndex), isLastFile);
}
private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
{
//logger.LogInformation("Opening live stream file {0}. Empty read limit: {1}", path, emptyReadLimit);
using (var inputStream = (FileStream)GetInputStream(path, allowAsync))
{
if (seekFile)
@@ -218,7 +194,11 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
private void TrySeek(FileStream stream, long offset)
{
//logger.LogInformation("TrySeek live stream");
if (!stream.CanSeek)
{
return;
}
try
{
stream.Seek(offset, SeekOrigin.End);

View File

@@ -19,6 +19,7 @@ using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.System;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.LiveTv.TunerHosts
{
@@ -145,7 +146,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts
if (protocol == MediaProtocol.Http)
{
// Use user-defined user-agent. If there isn't one, make it look like a browser.
httpHeaders["User-Agent"] = string.IsNullOrWhiteSpace(info.UserAgent) ?
httpHeaders[HeaderNames.UserAgent] = string.IsNullOrWhiteSpace(info.UserAgent) ?
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
info.UserAgent;
}

View File

@@ -1,97 +1,97 @@
{
"Albums": "Albums",
"AppDeviceValues": "App: {0}, Device: {1}",
"Application": "Application",
"Artists": "Artists",
"AuthenticationSucceededWithUserName": "{0} successfully authenticated",
"Books": "Books",
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
"Channels": "Channels",
"ChapterNameValue": "Chapter {0}",
"Collections": "Collections",
"DeviceOfflineWithName": "{0} has disconnected",
"DeviceOnlineWithName": "{0} is connected",
"FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
"Favorites": "Favorites",
"Folders": "Folders",
"Genres": "Genres",
"HeaderAlbumArtists": "Album Artists",
"HeaderCameraUploads": "Camera Uploads",
"HeaderContinueWatching": "Continue Watching",
"HeaderFavoriteAlbums": "Favorite Albums",
"HeaderFavoriteArtists": "Favorite Artists",
"HeaderFavoriteEpisodes": "Favorite Episodes",
"HeaderFavoriteShows": "Favorite Shows",
"HeaderFavoriteSongs": "Favorite Songs",
"HeaderLiveTV": "Live TV",
"HeaderNextUp": "Next Up",
"HeaderRecordingGroups": "Recording Groups",
"HomeVideos": "Home videos",
"Inherit": "Inherit",
"ItemAddedWithName": "{0} was added to the library",
"ItemRemovedWithName": "{0} was removed from the library",
"LabelIpAddressValue": "Ip address: {0}",
"LabelRunningTimeValue": "Running time: {0}",
"Latest": "Latest",
"MessageApplicationUpdated": "Jellyfin Server has been updated",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
"MessageServerConfigurationUpdated": "Server configuration has been updated",
"MixedContent": "Mixed content",
"Movies": "Movies",
"Music": "Music",
"MusicVideos": "Music videos",
"NameInstallFailed": "{0} installation failed",
"NameSeasonNumber": "Season {0}",
"NameSeasonUnknown": "Season Unknown",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
"NotificationOptionApplicationUpdateAvailable": "Application update available",
"NotificationOptionApplicationUpdateInstalled": "Application update installed",
"NotificationOptionAudioPlayback": "Audio playback started",
"NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
"NotificationOptionCameraImageUploaded": "Camera image uploaded",
"NotificationOptionInstallationFailed": "Installation failure",
"NotificationOptionNewLibraryContent": "New content added",
"NotificationOptionPluginError": "Plugin failure",
"NotificationOptionPluginInstalled": "Plugin installed",
"NotificationOptionPluginUninstalled": "Plugin uninstalled",
"NotificationOptionPluginUpdateInstalled": "Plugin update installed",
"NotificationOptionServerRestartRequired": "Server restart required",
"NotificationOptionTaskFailed": "Scheduled task failure",
"NotificationOptionUserLockedOut": "User locked out",
"NotificationOptionVideoPlayback": "Video playback started",
"NotificationOptionVideoPlaybackStopped": "Video playback stopped",
"Photos": "Photos",
"Playlists": "Playlists",
"Albums": "Álbumes",
"AppDeviceValues": "Aplicación: {0}, Dispositivo: {1}",
"Application": "Aplicación",
"Artists": "Artistas",
"AuthenticationSucceededWithUserName": "{0} autenticado correctamente",
"Books": "Libros",
"CameraImageUploadedFrom": "Se ha subido una nueva imagen de cámara desde {0}",
"Channels": "Canales",
"ChapterNameValue": "Capítulo {0}",
"Collections": "Colecciones",
"DeviceOfflineWithName": "{0} se ha desconectado",
"DeviceOnlineWithName": "{0} está conectado",
"FailedLoginAttemptWithUserName": "Error al intentar iniciar sesión desde {0}",
"Favorites": "Favoritos",
"Folders": "Carpetas",
"Genres": "Géneros",
"HeaderAlbumArtists": "Artistas de álbumes",
"HeaderCameraUploads": "Subidas de cámara",
"HeaderContinueWatching": "Continuar viendo",
"HeaderFavoriteAlbums": "Álbumes favoritos",
"HeaderFavoriteArtists": "Artistas favoritos",
"HeaderFavoriteEpisodes": "Episodios favoritos",
"HeaderFavoriteShows": "Programas favoritos",
"HeaderFavoriteSongs": "Canciones favoritas",
"HeaderLiveTV": "TV en vivo",
"HeaderNextUp": "Continuar Viendo",
"HeaderRecordingGroups": "Grupos de grabación",
"HomeVideos": "Videos caseros",
"Inherit": "Heredar",
"ItemAddedWithName": "{0} se ha añadido a la biblioteca",
"ItemRemovedWithName": "{0} ha sido eliminado de la biblioteca",
"LabelIpAddressValue": "Dirección IP: {0}",
"LabelRunningTimeValue": "Tiempo de funcionamiento: {0}",
"Latest": "Últimos",
"MessageApplicationUpdated": "El servidor Jellyfin fue actualizado",
"MessageApplicationUpdatedTo": "Se ha actualizado el servidor Jellyfin a la versión {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Fue actualizada la sección {0} de la configuración del servidor",
"MessageServerConfigurationUpdated": "Fue actualizada la configuración del servidor",
"MixedContent": "Contenido mixto",
"Movies": "Películas",
"Music": "Música",
"MusicVideos": "Videos musicales",
"NameInstallFailed": "{0} error de instalación",
"NameSeasonNumber": "Temporada {0}",
"NameSeasonUnknown": "Temporada desconocida",
"NewVersionIsAvailable": "Disponible una nueva versión de Jellyfin para descargar.",
"NotificationOptionApplicationUpdateAvailable": "Actualización de la aplicación disponible",
"NotificationOptionApplicationUpdateInstalled": "Actualización de la aplicación instalada",
"NotificationOptionAudioPlayback": "Se inició la reproducción de audio",
"NotificationOptionAudioPlaybackStopped": "Se detuvo la reproducción de audio",
"NotificationOptionCameraImageUploaded": "Imagen de la cámara cargada",
"NotificationOptionInstallationFailed": "Error de instalación",
"NotificationOptionNewLibraryContent": "Nuevo contenido añadido",
"NotificationOptionPluginError": "Error en plugin",
"NotificationOptionPluginInstalled": "Plugin instalado",
"NotificationOptionPluginUninstalled": "Plugin desinstalado",
"NotificationOptionPluginUpdateInstalled": "Actualización del complemento instalada",
"NotificationOptionServerRestartRequired": "Se requiere reinicio del servidor",
"NotificationOptionTaskFailed": "Error de tarea programada",
"NotificationOptionUserLockedOut": "Usuario bloqueado",
"NotificationOptionVideoPlayback": "Se inició la reproducción de video",
"NotificationOptionVideoPlaybackStopped": "Reproducción de video detenida",
"Photos": "Fotos",
"Playlists": "Listas de reproducción",
"Plugin": "Plugin",
"PluginInstalledWithName": "{0} was installed",
"PluginUninstalledWithName": "{0} was uninstalled",
"PluginUpdatedWithName": "{0} was updated",
"ProviderValue": "Provider: {0}",
"ScheduledTaskFailedWithName": "{0} failed",
"ScheduledTaskStartedWithName": "{0} started",
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
"PluginInstalledWithName": "{0} fue instalado",
"PluginUninstalledWithName": "{0} fue desinstalado",
"PluginUpdatedWithName": "{0} fue actualizado",
"ProviderValue": "Proveedor: {0}",
"ScheduledTaskFailedWithName": "{0} falló",
"ScheduledTaskStartedWithName": "{0} iniciada",
"ServerNameNeedsToBeRestarted": "{0} necesita ser reiniciado",
"Shows": "Series",
"Songs": "Songs",
"StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
"Songs": "Canciones",
"StartupEmbyServerIsLoading": "Jellyfin Server se está cargando. Vuelve a intentarlo en breve.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
"SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
"SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
"Sync": "Sync",
"System": "System",
"TvShows": "TV Shows",
"User": "User",
"UserCreatedWithName": "User {0} has been created",
"UserDeletedWithName": "User {0} has been deleted",
"UserDownloadingItemWithValues": "{0} is downloading {1}",
"UserLockedOutWithName": "User {0} has been locked out",
"UserOfflineFromDevice": "{0} has disconnected from {1}",
"UserOnlineFromDevice": "{0} is online from {1}",
"UserPasswordChangedWithName": "Password has been changed for user {0}",
"UserPolicyUpdatedWithName": "User policy has been updated for {0}",
"UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
"UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
"ValueSpecialEpisodeName": "Special - {0}",
"VersionNumber": "Version {0}"
"SubtitleDownloadFailureFromForItem": "Fallo de descarga de subtítulos desde {0} para {1}",
"SubtitlesDownloadedForItem": "Descargar subtítulos para {0}",
"Sync": "Sincronizar",
"System": "Sistema",
"TvShows": "Series de TV",
"User": "Usuario",
"UserCreatedWithName": "El usuario {0} ha sido creado",
"UserDeletedWithName": "El usuario {0} ha sido borrado",
"UserDownloadingItemWithValues": "{0} está descargando {1}",
"UserLockedOutWithName": "El usuario {0} ha sido bloqueado",
"UserOfflineFromDevice": "{0} se ha desconectado de {1}",
"UserOnlineFromDevice": "{0} está en línea desde {1}",
"UserPasswordChangedWithName": "Se ha cambiado la contraseña para el usuario {0}",
"UserPolicyUpdatedWithName": "Actualizada política de usuario para {0}",
"UserStartedPlayingItemWithValues": "{0} está reproduciendo {1} en {2}",
"UserStoppedPlayingItemWithValues": "{0} ha terminado de reproducir {1} en {2}",
"ValueHasBeenAddedToLibrary": "{0} ha sido añadido a tu biblioteca multimedia",
"ValueSpecialEpisodeName": "Especial - {0}",
"VersionNumber": "Versión {0}"
}

View File

@@ -1,97 +1,97 @@
{
"Albums": "Albums",
"AppDeviceValues": "App: {0}, Device: {1}",
"AppDeviceValues": "Application : {0}, Appareil : {1}",
"Application": "Application",
"Artists": "Artists",
"AuthenticationSucceededWithUserName": "{0} successfully authenticated",
"Books": "Books",
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
"Channels": "Channels",
"ChapterNameValue": "Chapter {0}",
"Artists": "Artistes",
"AuthenticationSucceededWithUserName": "{0} s'est authentifié avec succès",
"Books": "Livres",
"CameraImageUploadedFrom": "Une nouvelle image de caméra a été téléchargée depuis {0}",
"Channels": "Chaînes",
"ChapterNameValue": "Chapitre {0}",
"Collections": "Collections",
"DeviceOfflineWithName": "{0} has disconnected",
"DeviceOnlineWithName": "{0} is connected",
"FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
"Favorites": "Favorites",
"Folders": "Folders",
"DeviceOfflineWithName": "{0} s'est déconnecté",
"DeviceOnlineWithName": "{0} est connecté",
"FailedLoginAttemptWithUserName": "Échec d'une tentative de connexion de {0}",
"Favorites": "Favoris",
"Folders": "Dossiers",
"Genres": "Genres",
"HeaderAlbumArtists": "Album Artists",
"HeaderCameraUploads": "Camera Uploads",
"HeaderAlbumArtists": "Artistes de l'album",
"HeaderCameraUploads": "Photos transférées",
"HeaderContinueWatching": "Continuer à regarder",
"HeaderFavoriteAlbums": "Favorite Albums",
"HeaderFavoriteArtists": "Favorite Artists",
"HeaderFavoriteEpisodes": "Favorite Episodes",
"HeaderFavoriteShows": "Favorite Shows",
"HeaderFavoriteSongs": "Favorite Songs",
"HeaderLiveTV": "Live TV",
"HeaderFavoriteAlbums": "Albums favoris",
"HeaderFavoriteArtists": "Artistes favoris",
"HeaderFavoriteEpisodes": "Épisodes favoris",
"HeaderFavoriteShows": "Séries favorites",
"HeaderFavoriteSongs": "Chansons favorites",
"HeaderLiveTV": "TV en direct",
"HeaderNextUp": "À Suivre",
"HeaderRecordingGroups": "Recording Groups",
"HomeVideos": "Home videos",
"Inherit": "Inherit",
"ItemAddedWithName": "{0} was added to the library",
"ItemRemovedWithName": "{0} was removed from the library",
"LabelIpAddressValue": "Ip address: {0}",
"LabelRunningTimeValue": "Running time: {0}",
"Latest": "Latest",
"MessageApplicationUpdated": "Jellyfin Server has been updated",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
"MessageServerConfigurationUpdated": "Server configuration has been updated",
"MixedContent": "Mixed content",
"Movies": "Movies",
"Music": "Music",
"MusicVideos": "Music videos",
"NameInstallFailed": "{0} installation failed",
"NameSeasonNumber": "Season {0}",
"NameSeasonUnknown": "Season Unknown",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
"NotificationOptionApplicationUpdateAvailable": "Application update available",
"NotificationOptionApplicationUpdateInstalled": "Application update installed",
"NotificationOptionAudioPlayback": "Audio playback started",
"NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
"NotificationOptionCameraImageUploaded": "Camera image uploaded",
"NotificationOptionInstallationFailed": "Installation failure",
"NotificationOptionNewLibraryContent": "New content added",
"NotificationOptionPluginError": "Plugin failure",
"NotificationOptionPluginInstalled": "Plugin installed",
"NotificationOptionPluginUninstalled": "Plugin uninstalled",
"NotificationOptionPluginUpdateInstalled": "Plugin update installed",
"NotificationOptionServerRestartRequired": "Server restart required",
"NotificationOptionTaskFailed": "Scheduled task failure",
"NotificationOptionUserLockedOut": "User locked out",
"NotificationOptionVideoPlayback": "Video playback started",
"NotificationOptionVideoPlaybackStopped": "Video playback stopped",
"HeaderRecordingGroups": "Groupes d'enregistrements",
"HomeVideos": "Vidéos personnelles",
"Inherit": "riter",
"ItemAddedWithName": "{0} a été ajouté à la médiathèque",
"ItemRemovedWithName": "{0} a été supprimé de la médiathèque",
"LabelIpAddressValue": "Adresse IP : {0}",
"LabelRunningTimeValue": "Durée : {0}",
"Latest": "Derniers",
"MessageApplicationUpdated": "Le serveur Jellyfin a été mis à jour",
"MessageApplicationUpdatedTo": "Le serveur Jellyfin a été mis à jour vers la version {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "La configuration de la section {0} du serveur a été mise à jour",
"MessageServerConfigurationUpdated": "La configuration du serveur a été mise à jour",
"MixedContent": "Contenu mixte",
"Movies": "Films",
"Music": "Musique",
"MusicVideos": "Vidéos musicales",
"NameInstallFailed": "{0} échec d'installation",
"NameSeasonNumber": "Saison {0}",
"NameSeasonUnknown": "Saison Inconnue",
"NewVersionIsAvailable": "Une nouvelle version du serveur Jellyfin est disponible au téléchargement.",
"NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
"NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
"NotificationOptionAudioPlayback": "Lecture audio démarrée",
"NotificationOptionAudioPlaybackStopped": "Lecture audio arrêtée",
"NotificationOptionCameraImageUploaded": "L'image de l'appareil photo a été transférée",
"NotificationOptionInstallationFailed": "Échec d'installation",
"NotificationOptionNewLibraryContent": "Nouveau contenu ajouté",
"NotificationOptionPluginError": "Erreur d'extension",
"NotificationOptionPluginInstalled": "Extension installée",
"NotificationOptionPluginUninstalled": "Extension désinstallée",
"NotificationOptionPluginUpdateInstalled": "Mise à jour d'extension installée",
"NotificationOptionServerRestartRequired": "Un redémarrage du serveur est requis",
"NotificationOptionTaskFailed": "Échec de tâche planifiée",
"NotificationOptionUserLockedOut": "Utilisateur verrouillé",
"NotificationOptionVideoPlayback": "Lecture vidéo démarrée",
"NotificationOptionVideoPlaybackStopped": "Lecture vidéo arrêtée",
"Photos": "Photos",
"Playlists": "Playlists",
"Plugin": "Plugin",
"PluginInstalledWithName": "{0} was installed",
"PluginUninstalledWithName": "{0} was uninstalled",
"PluginUpdatedWithName": "{0} was updated",
"ProviderValue": "Provider: {0}",
"ScheduledTaskFailedWithName": "{0} failed",
"ScheduledTaskStartedWithName": "{0} started",
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
"Shows": "Series",
"Songs": "Songs",
"StartupEmbyServerIsLoading": "Jellyfin Server is loading. Please try again shortly.",
"Playlists": "Listes de lecture",
"Plugin": "Extension",
"PluginInstalledWithName": "{0} a été installé",
"PluginUninstalledWithName": "{0} a été désinstallé",
"PluginUpdatedWithName": "{0} a été mis à jour",
"ProviderValue": "Fournisseur : {0}",
"ScheduledTaskFailedWithName": "{0} a échoué",
"ScheduledTaskStartedWithName": "{0} a commencé",
"ServerNameNeedsToBeRestarted": "{0} doit être redémarré",
"Shows": "Émissions",
"Songs": "Chansons",
"StartupEmbyServerIsLoading": "Le serveur Jellyfin est en cours de chargement. Veuillez réessayer dans quelques instants.",
"SubtitleDownloadFailureForItem": "Subtitles failed to download for {0}",
"SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
"SubtitlesDownloadedForItem": "Subtitles downloaded for {0}",
"Sync": "Sync",
"System": "System",
"TvShows": "TV Shows",
"User": "User",
"UserCreatedWithName": "User {0} has been created",
"UserDeletedWithName": "User {0} has been deleted",
"UserDownloadingItemWithValues": "{0} is downloading {1}",
"UserLockedOutWithName": "User {0} has been locked out",
"UserOfflineFromDevice": "{0} has disconnected from {1}",
"UserOnlineFromDevice": "{0} is online from {1}",
"UserPasswordChangedWithName": "Password has been changed for user {0}",
"UserPolicyUpdatedWithName": "User policy has been updated for {0}",
"UserStartedPlayingItemWithValues": "{0} is playing {1} on {2}",
"UserStoppedPlayingItemWithValues": "{0} has finished playing {1} on {2}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
"SubtitleDownloadFailureFromForItem": "Échec du téléchargement des sous-titres depuis {0} pour {1}",
"SubtitlesDownloadedForItem": "Les sous-titres de {0} ont été téléchargés",
"Sync": "Synchroniser",
"System": "Système",
"TvShows": "Séries Télé",
"User": "Utilisateur",
"UserCreatedWithName": "L'utilisateur {0} a été créé",
"UserDeletedWithName": "L'utilisateur {0} a été supprimé",
"UserDownloadingItemWithValues": "{0} est en train de télécharger {1}",
"UserLockedOutWithName": "L'utilisateur {0} a été verrouillé",
"UserOfflineFromDevice": "{0} s'est déconnecté depuis {1}",
"UserOnlineFromDevice": "{0} s'est connecté depuis {1}",
"UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié",
"UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
"UserStartedPlayingItemWithValues": "{0} est en train de lire {1} sur {2}",
"UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}",
"ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre médiathèque",
"ValueSpecialEpisodeName": "Spécial - {0}",
"VersionNumber": "Version {0}"
}

View File

@@ -44,7 +44,7 @@
"NameInstallFailed": "{0} échec d'installation",
"NameSeasonNumber": "Saison {0}",
"NameSeasonUnknown": "Saison Inconnue",
"NewVersionIsAvailable": "Une nouvelle version d'Jellyfin Serveur est disponible au téléchargement.",
"NewVersionIsAvailable": "Une nouvelle version de Jellyfin Serveur est disponible au téléchargement.",
"NotificationOptionApplicationUpdateAvailable": "Mise à jour de l'application disponible",
"NotificationOptionApplicationUpdateInstalled": "Mise à jour de l'application installée",
"NotificationOptionAudioPlayback": "Lecture audio démarrée",
@@ -89,7 +89,7 @@
"UserOnlineFromDevice": "{0} s'est connecté depuis {1}",
"UserPasswordChangedWithName": "Le mot de passe pour l'utilisateur {0} a été modifié",
"UserPolicyUpdatedWithName": "La politique de l'utilisateur a été mise à jour pour {0}",
"UserStartedPlayingItemWithValues": "{0} est entrain de lire {1} sur {2}",
"UserStartedPlayingItemWithValues": "{0} est en train de lire {1} sur {2}",
"UserStoppedPlayingItemWithValues": "{0} vient d'arrêter la lecture de {1} sur {2}",
"ValueHasBeenAddedToLibrary": "{0} a été ajouté à votre librairie",
"ValueSpecialEpisodeName": "Spécial - {0}",

View File

@@ -1,8 +1,8 @@
{
"Albums": "Albums",
"Albums": "אלבומים",
"AppDeviceValues": "App: {0}, Device: {1}",
"Application": "Application",
"Artists": "Artists",
"Application": "אפליקציה",
"Artists": "אמנים",
"AuthenticationSucceededWithUserName": "{0} successfully authenticated",
"Books": "ספרים",
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",

View File

@@ -34,17 +34,17 @@
"LabelRunningTimeValue": "Durata: {0}",
"Latest": "Più recenti",
"MessageApplicationUpdated": "Il Server Jellyfin è stato aggiornato",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"MessageApplicationUpdatedTo": "Jellyfin Server è stato aggiornato a {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "La sezione {0} della configurazione server è stata aggiornata",
"MessageServerConfigurationUpdated": "La configurazione del server è stata aggiornata",
"MixedContent": "Contenuto misto",
"Movies": "Film",
"Music": "Musica",
"MusicVideos": "Video musicali",
"NameInstallFailed": "{0} installation failed",
"NameInstallFailed": "{0} installazione fallita",
"NameSeasonNumber": "Stagione {0}",
"NameSeasonUnknown": "Stagione sconosciuto",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
"NewVersionIsAvailable": "Una nuova versione di Jellyfin Server è disponibile per il download.",
"NotificationOptionApplicationUpdateAvailable": "Aggiornamento dell'applicazione disponibile",
"NotificationOptionApplicationUpdateInstalled": "Aggiornamento dell'applicazione installato",
"NotificationOptionAudioPlayback": "La riproduzione audio è iniziata",
@@ -70,12 +70,12 @@
"ProviderValue": "Provider: {0}",
"ScheduledTaskFailedWithName": "{0} fallito",
"ScheduledTaskStartedWithName": "{0} avviati",
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
"ServerNameNeedsToBeRestarted": "{0} deve essere riavviato",
"Shows": "Programmi",
"Songs": "Canzoni",
"StartupEmbyServerIsLoading": "Jellyfin server si sta avviando. Per favore riprova più tardi.",
"SubtitleDownloadFailureForItem": "Impossibile scaricare i sottotitoli per {0}",
"SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
"SubtitleDownloadFailureFromForItem": "Impossibile scaricare i sottotitoli da {0} per {1}",
"SubtitlesDownloadedForItem": "Sottotitoli scaricati per {0}",
"Sync": "Sincronizza",
"System": "Sistema",
@@ -91,7 +91,7 @@
"UserPolicyUpdatedWithName": "La politica dell'utente è stata aggiornata per {0}",
"UserStartedPlayingItemWithValues": "{0} ha avviato la riproduzione di {1}",
"UserStoppedPlayingItemWithValues": "{0} ha interrotto la riproduzione di {1}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
"ValueHasBeenAddedToLibrary": "{0} è stato aggiunto alla tua libreria multimediale",
"ValueSpecialEpisodeName": "Speciale - {0}",
"VersionNumber": "Versione {0}"
}

View File

@@ -3,15 +3,15 @@
"AppDeviceValues": "Qoldanba: {0}, Qurylǵy: {1}",
"Application": "Qoldanba",
"Artists": "Oryndaýshylar",
"AuthenticationSucceededWithUserName": "{0} túpnusqalyǵyn rastalýy sátti",
"AuthenticationSucceededWithUserName": "{0} túpnusqalyq rastalýy sátti aıaqtaldy",
"Books": "Kitaptar",
"CameraImageUploadedFrom": "Jańa sýret {0} kamerasynan júktep alyndy",
"CameraImageUploadedFrom": "{0} kamerasynan jańa sýret júktep alyndy",
"Channels": "Arnalar",
"ChapterNameValue": "{0}-sahna",
"Collections": "Jıyntyqtar",
"DeviceOfflineWithName": "{0} ajyratylǵan",
"DeviceOnlineWithName": "{0} qosylǵan",
"FailedLoginAttemptWithUserName": "{0} tarapynan kirý áreketi sátsiz",
"FailedLoginAttemptWithUserName": "{0} tarapynan kirý áreketi sátsiz aıaqtaldy",
"Favorites": "Tańdaýlylar",
"Folders": "Qaltalar",
"Genres": "Janrlar",
@@ -28,13 +28,13 @@
"HeaderRecordingGroups": "Jazba toptary",
"HomeVideos": ılik beıneler",
"Inherit": "Muraǵa ıelený",
"ItemAddedWithName": "{0} tasyǵyshhanaǵa ústelindi",
"ItemAddedWithName": "{0} tasyǵyshhanaǵa ústeldi",
"ItemRemovedWithName": "{0} tasyǵyshhanadan alastaldy",
"LabelIpAddressValue": "IP-mekenjaıy: {0}",
"LabelRunningTimeValue": "Oınatý ýaqyty: {0}",
"Latest": "Eń keıingi",
"MessageApplicationUpdated": "Jellyfin Serveri jańartyldy",
"MessageApplicationUpdatedTo": "Jellyfin Serveri {0} deńgeıge jańartyldy",
"MessageApplicationUpdatedTo": "Jellyfin Serveri {0} nusqasyna jańartyldy",
"MessageNamedServerConfigurationUpdatedWithValue": "Server teńsheliminiń {0} bólimi jańartyldy",
"MessageServerConfigurationUpdated": "Server teńshelimi jańartyldy",
"MixedContent": "Aralas mazmun",

View File

@@ -5,7 +5,7 @@
"Artists": "Artistas",
"AuthenticationSucceededWithUserName": "{0} autenticado com sucesso",
"Books": "Livros",
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
"CameraImageUploadedFrom": "Uma nova imagem da câmera foi submetida de {0}",
"Channels": "Canais",
"ChapterNameValue": "Capítulo {0}",
"Collections": "Coletâneas",
@@ -30,21 +30,21 @@
"Inherit": "Herdar",
"ItemAddedWithName": "{0} foi adicionado à biblioteca",
"ItemRemovedWithName": "{0} foi removido da biblioteca",
"LabelIpAddressValue": "Endereço ip: {0}",
"LabelIpAddressValue": "Endereço IP: {0}",
"LabelRunningTimeValue": "Tempo de execução: {0}",
"Latest": "Recente",
"MessageApplicationUpdated": "O servidor Jellyfin foi atualizado",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"MessageApplicationUpdatedTo": "O Servidor Jellyfin foi atualizado para {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "A seção {0} da configuração do servidor foi atualizada",
"MessageServerConfigurationUpdated": "A configuração do servidor foi atualizada",
"MixedContent": "Conteúdo misto",
"Movies": "Filmes",
"Music": "Música",
"MusicVideos": "Vídeos musicais",
"NameInstallFailed": "{0} installation failed",
"NameInstallFailed": "A instalação de {0} falhou",
"NameSeasonNumber": "Temporada {0}",
"NameSeasonUnknown": "Temporada Desconhecida",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
"NewVersionIsAvailable": "Uma nova versão do servidor Jellyfin está disponível para download.",
"NotificationOptionApplicationUpdateAvailable": "Atualização de aplicativo disponível",
"NotificationOptionApplicationUpdateInstalled": "Atualização de aplicativo instalada",
"NotificationOptionAudioPlayback": "Reprodução de áudio iniciada",
@@ -70,12 +70,12 @@
"ProviderValue": "Provedor: {0}",
"ScheduledTaskFailedWithName": "{0} falhou",
"ScheduledTaskStartedWithName": "{0} iniciada",
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
"ServerNameNeedsToBeRestarted": "O servidor {0} precisa ser reiniciado",
"Shows": "Séries",
"Songs": "Músicas",
"StartupEmbyServerIsLoading": "O Servidor Jellyfin está carregando. Por favor tente novamente em breve.",
"SubtitleDownloadFailureForItem": "Download de legendas falhou para {0}",
"SubtitleDownloadFailureFromForItem": "Subtitles failed to download from {0} for {1}",
"SubtitleDownloadFailureFromForItem": "Houve um problema ao baixar as legendas de {0} para {1}",
"SubtitlesDownloadedForItem": "Legendas baixadas para {0}",
"Sync": "Sincronizar",
"System": "Sistema",
@@ -91,7 +91,7 @@
"UserPolicyUpdatedWithName": "A política de usuário foi atualizada para {0}",
"UserStartedPlayingItemWithValues": "{0} iniciou a reprodução de {1}",
"UserStoppedPlayingItemWithValues": "{0} parou de reproduzir {1}",
"ValueHasBeenAddedToLibrary": "{0} has been added to your media library",
"ValueHasBeenAddedToLibrary": "{0} foi adicionado a sua biblioteca",
"ValueSpecialEpisodeName": "Especial - {0}",
"VersionNumber": "Versão {0}"
}

View File

@@ -1,62 +1,62 @@
{
"Albums": "Albums",
"AppDeviceValues": "App: {0}, Device: {1}",
"Application": "Application",
"Artists": "Artists",
"AuthenticationSucceededWithUserName": "{0} successfully authenticated",
"Books": "Books",
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
"Channels": "Channels",
"ChapterNameValue": "Chapter {0}",
"Collections": "Collections",
"Albums": "Albumi",
"AppDeviceValues": "Aplikacija: {0}, Naprava: {1}",
"Application": "Aplikacija",
"Artists": "Izvajalci",
"AuthenticationSucceededWithUserName": "{0} preverjanje uspešno",
"Books": "Knjige",
"CameraImageUploadedFrom": "Nova fotografija je bila naložena z {0}",
"Channels": "Kanali",
"ChapterNameValue": "Poglavje {0}",
"Collections": "Zbirke",
"DeviceOfflineWithName": "{0} has disconnected",
"DeviceOnlineWithName": "{0} is connected",
"FailedLoginAttemptWithUserName": "Failed login attempt from {0}",
"Favorites": "Favorites",
"Folders": "Folders",
"Genres": "Genres",
"HeaderAlbumArtists": "Album Artists",
"HeaderCameraUploads": "Camera Uploads",
"HeaderContinueWatching": "Continue Watching",
"HeaderFavoriteAlbums": "Favorite Albums",
"HeaderFavoriteArtists": "Favorite Artists",
"HeaderFavoriteEpisodes": "Favorite Episodes",
"HeaderFavoriteShows": "Favorite Shows",
"HeaderFavoriteSongs": "Favorite Songs",
"HeaderLiveTV": "Live TV",
"HeaderNextUp": "Next Up",
"HeaderRecordingGroups": "Recording Groups",
"HomeVideos": "Home videos",
"Inherit": "Inherit",
"ItemAddedWithName": "{0} was added to the library",
"ItemRemovedWithName": "{0} was removed from the library",
"LabelIpAddressValue": "Ip address: {0}",
"LabelRunningTimeValue": "Running time: {0}",
"Latest": "Latest",
"MessageApplicationUpdated": "Jellyfin Server has been updated",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"DeviceOnlineWithName": "{0} je povezan",
"FailedLoginAttemptWithUserName": "Neuspešen poskus prijave z {0}",
"Favorites": "Priljubljeni",
"Folders": "Mape",
"Genres": "Zvrsti",
"HeaderAlbumArtists": "Izvajalci albuma",
"HeaderCameraUploads": "Posnetki kamere",
"HeaderContinueWatching": "Nadaljuj gledanje",
"HeaderFavoriteAlbums": "Priljubljeni albumi",
"HeaderFavoriteArtists": "Priljubljeni izvajalci",
"HeaderFavoriteEpisodes": "Priljubljene epizode",
"HeaderFavoriteShows": "Priljubljene serije",
"HeaderFavoriteSongs": "Priljubljene pesmi",
"HeaderLiveTV": "TV v živo",
"HeaderNextUp": "Sledi",
"HeaderRecordingGroups": "Zbirke posnetkov",
"HomeVideos": "Domači posnetki",
"Inherit": "Podeduj",
"ItemAddedWithName": "{0} je dodan v knjižnico",
"ItemRemovedWithName": "{0} je bil odstranjen iz knjižnice",
"LabelIpAddressValue": "IP naslov: {0}",
"LabelRunningTimeValue": "Čas trajanja: {0}",
"Latest": "Najnovejše",
"MessageApplicationUpdated": "Jellyfin strežnik je bil posodobljen",
"MessageApplicationUpdatedTo": "Jellyfin strežnik je bil posodobljen na {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
"MessageServerConfigurationUpdated": "Server configuration has been updated",
"MixedContent": "Mixed content",
"Movies": "Movies",
"Music": "Music",
"MusicVideos": "Music videos",
"NameInstallFailed": "{0} installation failed",
"NameSeasonNumber": "Season {0}",
"NameSeasonUnknown": "Season Unknown",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
"NotificationOptionApplicationUpdateAvailable": "Application update available",
"NotificationOptionApplicationUpdateInstalled": "Application update installed",
"NotificationOptionAudioPlayback": "Audio playback started",
"NotificationOptionAudioPlaybackStopped": "Audio playback stopped",
"NotificationOptionCameraImageUploaded": "Camera image uploaded",
"NotificationOptionInstallationFailed": "Installation failure",
"NotificationOptionNewLibraryContent": "New content added",
"NotificationOptionPluginError": "Plugin failure",
"NotificationOptionPluginInstalled": "Plugin installed",
"NotificationOptionPluginUninstalled": "Plugin uninstalled",
"NotificationOptionPluginUpdateInstalled": "Plugin update installed",
"NotificationOptionServerRestartRequired": "Server restart required",
"MessageServerConfigurationUpdated": "Nastavitve strežnika so bile posodobljene",
"MixedContent": "Razne vsebine",
"Movies": "Filmi",
"Music": "Glasba",
"MusicVideos": "Glasbeni posnetki",
"NameInstallFailed": "{0} namestitev neuspešna",
"NameSeasonNumber": "Sezona {0}",
"NameSeasonUnknown": "Season neznana",
"NewVersionIsAvailable": "Nova razničica Jellyfin strežnika je na voljo za prenos.",
"NotificationOptionApplicationUpdateAvailable": "Posodobitev aplikacije je na voljo",
"NotificationOptionApplicationUpdateInstalled": "Posodobitev aplikacije je bila nameščena",
"NotificationOptionAudioPlayback": "Predvajanje zvoka začeto",
"NotificationOptionAudioPlaybackStopped": "Predvajanje zvoka zaustavljeno",
"NotificationOptionCameraImageUploaded": "Posnetek kamere naložen",
"NotificationOptionInstallationFailed": "Napaka pri nameščanju",
"NotificationOptionNewLibraryContent": "Nove vsebine dodane",
"NotificationOptionPluginError": "Napaka dodatka",
"NotificationOptionPluginInstalled": "Dodatek nameščen",
"NotificationOptionPluginUninstalled": "Dodatek odstranjen",
"NotificationOptionPluginUpdateInstalled": "Posodobitev dodatka nameščena",
"NotificationOptionServerRestartRequired": "Potreben je ponovni zagon strežnika",
"NotificationOptionTaskFailed": "Scheduled task failure",
"NotificationOptionUserLockedOut": "User locked out",
"NotificationOptionVideoPlayback": "Video playback started",

View File

@@ -1,12 +1,12 @@
{
"Albums": "Albums",
"AppDeviceValues": "App: {0}, Device: {1}",
"Application": "Application",
"Artists": "Artists",
"AuthenticationSucceededWithUserName": "{0} successfully authenticated",
"Books": "Books",
"Albums": "Albümler",
"AppDeviceValues": "Uygulama: {0}, Aygıt: {1}",
"Application": "Uygulama",
"Artists": "Sanatçılar",
"AuthenticationSucceededWithUserName": "{0} başarı ile giriş yaptı",
"Books": "Kitaplar",
"CameraImageUploadedFrom": "A new camera image has been uploaded from {0}",
"Channels": "Channels",
"Channels": "Kanallar",
"ChapterNameValue": "Chapter {0}",
"Collections": "Collections",
"DeviceOfflineWithName": "{0} has disconnected",
@@ -17,8 +17,8 @@
"Genres": "Genres",
"HeaderAlbumArtists": "Album Artists",
"HeaderCameraUploads": "Camera Uploads",
"HeaderContinueWatching": "Continue Watching",
"HeaderFavoriteAlbums": "Favorite Albums",
"HeaderContinueWatching": "İzlemeye Devam Et",
"HeaderFavoriteAlbums": "Favori Albümler",
"HeaderFavoriteArtists": "Favorite Artists",
"HeaderFavoriteEpisodes": "Favorite Episodes",
"HeaderFavoriteShows": "Favori Showlar",
@@ -30,21 +30,21 @@
"Inherit": "Inherit",
"ItemAddedWithName": "{0} was added to the library",
"ItemRemovedWithName": "{0} was removed from the library",
"LabelIpAddressValue": "Ip address: {0}",
"LabelRunningTimeValue": "Running time: {0}",
"LabelIpAddressValue": "Ip adresi: {0}",
"LabelRunningTimeValue": "Çalışma süresi: {0}",
"Latest": "Latest",
"MessageApplicationUpdated": "Jellyfin Server has been updated",
"MessageApplicationUpdated": "Jellyfin Sunucusu güncellendi",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "Server configuration section {0} has been updated",
"MessageServerConfigurationUpdated": "Server configuration has been updated",
"MixedContent": "Mixed content",
"Movies": "Movies",
"Music": "Music",
"MusicVideos": "Music videos",
"NameInstallFailed": "{0} installation failed",
"NameSeasonNumber": "Season {0}",
"NameSeasonUnknown": "Season Unknown",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
"Music": "Müzik",
"MusicVideos": "Müzik videoları",
"NameInstallFailed": "{0} kurulum başarısız",
"NameSeasonNumber": "Sezon {0}",
"NameSeasonUnknown": "Bilinmeyen Sezon",
"NewVersionIsAvailable": "Jellyfin Sunucusunun yeni bir versiyonu indirmek için hazır.",
"NotificationOptionApplicationUpdateAvailable": "Application update available",
"NotificationOptionApplicationUpdateInstalled": "Application update installed",
"NotificationOptionAudioPlayback": "Audio playback started",

View File

@@ -34,14 +34,14 @@
"LabelRunningTimeValue": "运行时间:{0}",
"Latest": "最新",
"MessageApplicationUpdated": "Jellyfin 服务器已更新",
"MessageApplicationUpdatedTo": "Jellyfin Server has been updated to {0}",
"MessageApplicationUpdatedTo": "Jellyfin Server 的版本已更新为 {0}",
"MessageNamedServerConfigurationUpdatedWithValue": "服务器配置 {0} 部分已更新",
"MessageServerConfigurationUpdated": "服务器配置已更新",
"MixedContent": "混合内容",
"Movies": "电影",
"Music": "音乐",
"MusicVideos": "音乐视频",
"NameInstallFailed": "{0} installation failed",
"NameInstallFailed": "{0} 安装失败",
"NameSeasonNumber": "季 {0}",
"NameSeasonUnknown": "未知季",
"NewVersionIsAvailable": "A new version of Jellyfin Server is available for download.",
@@ -70,7 +70,7 @@
"ProviderValue": "提供商:{0}",
"ScheduledTaskFailedWithName": "{0} 已失败",
"ScheduledTaskStartedWithName": "{0} 已开始",
"ServerNameNeedsToBeRestarted": "{0} needs to be restarted",
"ServerNameNeedsToBeRestarted": "{0} 需要重新启动",
"Shows": "节目",
"Songs": "歌曲",
"StartupEmbyServerIsLoading": "Jellyfin 服务器加载中。请稍后再试。",

View File

@@ -11,7 +11,6 @@ using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
@@ -35,7 +34,6 @@ namespace Emby.Server.Implementations.Localization
private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
private readonly IFileSystem _fileSystem;
private readonly IJsonSerializer _jsonSerializer;
private readonly ILogger _logger;
private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
@@ -44,130 +42,65 @@ namespace Emby.Server.Implementations.Localization
/// Initializes a new instance of the <see cref="LocalizationManager" /> class.
/// </summary>
/// <param name="configurationManager">The configuration manager.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="loggerFactory">The logger factory</param>
public LocalizationManager(
IServerConfigurationManager configurationManager,
IFileSystem fileSystem,
IJsonSerializer jsonSerializer,
ILoggerFactory loggerFactory)
{
_configurationManager = configurationManager;
_fileSystem = fileSystem;
_jsonSerializer = jsonSerializer;
_logger = loggerFactory.CreateLogger(nameof(LocalizationManager));
}
public async Task LoadAll()
{
const string ratingsResource = "Emby.Server.Implementations.Localization.Ratings.";
Directory.CreateDirectory(LocalizationPath);
var existingFiles = GetRatingsFiles(LocalizationPath).Select(Path.GetFileName);
const string RatingsResource = "Emby.Server.Implementations.Localization.Ratings.";
// Extract from the assembly
foreach (var resource in _assembly.GetManifestResourceNames())
{
if (!resource.StartsWith(ratingsResource))
if (!resource.StartsWith(RatingsResource, StringComparison.Ordinal))
{
continue;
}
string filename = "ratings-" + resource.Substring(ratingsResource.Length);
string countryCode = resource.Substring(RatingsResource.Length, 2);
var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
if (existingFiles.Contains(filename))
using (var str = _assembly.GetManifestResourceStream(resource))
using (var reader = new StreamReader(str))
{
continue;
}
using (var stream = _assembly.GetManifestResourceStream(resource))
{
string target = Path.Combine(LocalizationPath, filename);
_logger.LogInformation("Extracting ratings to {0}", target);
using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
string line;
while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
{
await stream.CopyToAsync(fs);
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
string[] parts = line.Split(',');
if (parts.Length == 2
&& int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out var value))
{
dict.Add(parts[0], new ParentalRating { Name = parts[0], Value = value });
}
#if DEBUG
else
{
_logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
}
#endif
}
}
_allParentalRatings[countryCode] = dict;
}
foreach (var file in GetRatingsFiles(LocalizationPath))
{
await LoadRatings(file);
}
LoadAdditionalRatings();
await LoadCultures();
await LoadCultures().ConfigureAwait(false);
}
private void LoadAdditionalRatings()
{
LoadRatings("au", new[]
{
new ParentalRating("AU-G", 1),
new ParentalRating("AU-PG", 5),
new ParentalRating("AU-M", 6),
new ParentalRating("AU-MA15+", 7),
new ParentalRating("AU-M15+", 8),
new ParentalRating("AU-R18+", 9),
new ParentalRating("AU-X18+", 10),
new ParentalRating("AU-RC", 11)
});
LoadRatings("be", new[]
{
new ParentalRating("BE-AL", 1),
new ParentalRating("BE-MG6", 2),
new ParentalRating("BE-6", 3),
new ParentalRating("BE-9", 5),
new ParentalRating("BE-12", 6),
new ParentalRating("BE-16", 8)
});
LoadRatings("de", new[]
{
new ParentalRating("DE-0", 1),
new ParentalRating("FSK-0", 1),
new ParentalRating("DE-6", 5),
new ParentalRating("FSK-6", 5),
new ParentalRating("DE-12", 7),
new ParentalRating("FSK-12", 7),
new ParentalRating("DE-16", 8),
new ParentalRating("FSK-16", 8),
new ParentalRating("DE-18", 9),
new ParentalRating("FSK-18", 9)
});
LoadRatings("ru", new[]
{
new ParentalRating("RU-0+", 1),
new ParentalRating("RU-6+", 3),
new ParentalRating("RU-12+", 7),
new ParentalRating("RU-16+", 9),
new ParentalRating("RU-18+", 10)
});
}
private void LoadRatings(string country, ParentalRating[] ratings)
{
_allParentalRatings[country] = ratings.ToDictionary(i => i.Name);
}
private IEnumerable<string> GetRatingsFiles(string directory)
=> _fileSystem.GetFilePaths(directory, false)
.Where(i => string.Equals(Path.GetExtension(i), ".csv", StringComparison.OrdinalIgnoreCase))
.Where(i => Path.GetFileName(i).StartsWith("ratings-", StringComparison.OrdinalIgnoreCase));
/// <summary>
/// Gets the localization path.
/// </summary>
/// <value>The localization path.</value>
public string LocalizationPath
=> Path.Combine(_configurationManager.ApplicationPaths.ProgramDataPath, "localization");
public string NormalizeFormKD(string text)
=> text.Normalize(NormalizationForm.FormKD);
@@ -184,14 +117,14 @@ namespace Emby.Server.Implementations.Localization
{
List<CultureDto> list = new List<CultureDto>();
const string path = "Emby.Server.Implementations.Localization.iso6392.txt";
const string ResourcePath = "Emby.Server.Implementations.Localization.iso6392.txt";
using (var stream = _assembly.GetManifestResourceStream(path))
using (var stream = _assembly.GetManifestResourceStream(ResourcePath))
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
var line = await reader.ReadLineAsync().ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(line))
{
@@ -217,11 +150,11 @@ namespace Emby.Server.Implementations.Localization
string[] threeletterNames;
if (string.IsNullOrWhiteSpace(parts[1]))
{
threeletterNames = new [] { parts[0] };
threeletterNames = new[] { parts[0] };
}
else
{
threeletterNames = new [] { parts[0], parts[1] };
threeletterNames = new[] { parts[0], parts[1] };
}
list.Add(new CultureDto
@@ -281,6 +214,7 @@ namespace Emby.Server.Implementations.Localization
/// Gets the ratings.
/// </summary>
/// <param name="countryCode">The country code.</param>
/// <returns>The ratings</returns>
private Dictionary<string, ParentalRating> GetRatings(string countryCode)
{
_allParentalRatings.TryGetValue(countryCode, out var value);
@@ -288,52 +222,14 @@ namespace Emby.Server.Implementations.Localization
return value;
}
/// <summary>
/// Loads the ratings.
/// </summary>
/// <param name="file">The file.</param>
/// <returns>Dictionary{System.StringParentalRating}.</returns>
private async Task LoadRatings(string file)
{
Dictionary<string, ParentalRating> dict
= new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
using (var str = File.OpenRead(file))
using (var reader = new StreamReader(str))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
string[] parts = line.Split(',');
if (parts.Length == 2
&& int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out var value))
{
dict.Add(parts[0], (new ParentalRating { Name = parts[0], Value = value }));
}
#if DEBUG
else
{
_logger.LogWarning("Misformed line in {Path}", file);
}
#endif
}
}
var countryCode = Path.GetFileNameWithoutExtension(file).Split('-')[1];
_allParentalRatings[countryCode] = dict;
}
private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" };
/// <inheritdoc />
/// <summary>
/// Gets the rating level.
/// </summary>
/// <param name="rating">Rating field</param>
/// <returns>The rating level</returns>&gt;
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
@@ -405,6 +301,7 @@ namespace Emby.Server.Implementations.Localization
{
culture = _configurationManager.Configuration.UICulture;
}
if (string.IsNullOrEmpty(culture))
{
culture = DefaultCulture;
@@ -450,8 +347,8 @@ namespace Emby.Server.Implementations.Localization
var namespaceName = GetType().Namespace + "." + prefix;
await CopyInto(dictionary, namespaceName + "." + baseFilename);
await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture));
await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false);
await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false);
return dictionary;
}
@@ -463,7 +360,7 @@ namespace Emby.Server.Implementations.Localization
// If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain
if (stream != null)
{
var dict = await _jsonSerializer.DeserializeFromStreamAsync<Dictionary<string, string>>(stream);
var dict = await _jsonSerializer.DeserializeFromStreamAsync<Dictionary<string, string>>(stream).ConfigureAwait(false);
foreach (var key in dict.Keys)
{

View File

@@ -0,0 +1,8 @@
AU-G,1
AU-PG,5
AU-M,6
AU-MA15+,7
AU-M15+,8
AU-R18+,9
AU-X18+,10
AU-RC,11
1 AU-G 1
2 AU-PG 5
3 AU-M 6
4 AU-MA15+ 7
5 AU-M15+ 8
6 AU-R18+ 9
7 AU-X18+ 10
8 AU-RC 11

View File

@@ -0,0 +1,6 @@
BE-AL,1
BE-MG6,2
BE-6,3
BE-9,5
BE-12,6
BE-16,8
1 BE-AL 1
2 BE-MG6 2
3 BE-6 3
4 BE-9 5
5 BE-12 6
6 BE-16 8

View File

@@ -0,0 +1,10 @@
DE-0,1
FSK-0,1
DE-6,5
FSK-6,5
DE-12,7
FSK-12,7
DE-16,8
FSK-16,8
DE-18,9
FSK-18,9
1 DE-0 1
2 FSK-0 1
3 DE-6 5
4 FSK-6 5
5 DE-12 7
6 FSK-12 7
7 DE-16 8
8 FSK-16 8
9 DE-18 9
10 FSK-18 9

View File

@@ -0,0 +1,5 @@
RU-0+,1
RU-6+,3
RU-12+,7
RU-16+,9
RU-18+,10
1 RU-0+ 1
2 RU-6+ 3
3 RU-12+ 7
4 RU-16+ 9
5 RU-18+ 10

View File

@@ -202,6 +202,10 @@ namespace Emby.Server.Implementations.MediaEncoder
private static List<string> GetSavedChapterImages(Video video, IDirectoryService directoryService)
{
var path = GetChapterImagesPath(video);
if (!Directory.Exists(path))
{
return new List<string>();
}
try
{

View File

@@ -0,0 +1,39 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using WebSocketManager = Emby.Server.Implementations.WebSockets.WebSocketManager;
namespace Emby.Server.Implementations.Middleware
{
public class WebSocketMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<WebSocketMiddleware> _logger;
private readonly WebSocketManager _webSocketManager;
public WebSocketMiddleware(RequestDelegate next, ILogger<WebSocketMiddleware> logger, WebSocketManager webSocketManager)
{
_next = next;
_logger = logger;
_webSocketManager = webSocketManager;
}
public async Task Invoke(HttpContext httpContext)
{
_logger.LogInformation("Handling request: " + httpContext.Request.Path);
if (httpContext.WebSockets.IsWebSocketRequest)
{
var webSocketContext = await httpContext.WebSockets.AcceptWebSocketAsync(null).ConfigureAwait(false);
if (webSocketContext != null)
{
await _webSocketManager.OnWebSocketConnected(webSocketContext);
}
}
else
{
await _next.Invoke(httpContext);
}
}
}
}

View File

@@ -1,66 +0,0 @@
using System;
namespace Emby.Server.Implementations.Net
{
/// <summary>
/// Correclty implements the <see cref="IDisposable"/> interface and pattern for an object containing only managed resources, and adds a few common niceities not on the interface such as an <see cref="IsDisposed"/> property.
/// </summary>
public abstract class DisposableManagedObjectBase : IDisposable
{
#region Public Methods
/// <summary>
/// Override this method and dispose any objects you own the lifetime of if disposing is true;
/// </summary>
/// <param name="disposing">True if managed objects should be disposed, if false, only unmanaged resources should be released.</param>
protected abstract void Dispose(bool disposing);
//TODO Remove and reimplement using the IsDisposed property directly.
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if the <see cref="IsDisposed"/> property is true.
/// </summary>
/// <seealso cref="IsDisposed"/>
/// <exception cref="ObjectDisposedException">Thrown if the <see cref="IsDisposed"/> property is true.</exception>
/// <seealso cref="Dispose()"/>
protected virtual void ThrowIfDisposed()
{
if (IsDisposed) throw new ObjectDisposedException(GetType().Name);
}
#endregion
#region Public Properties
/// <summary>
/// Sets or returns a boolean indicating whether or not this instance has been disposed.
/// </summary>
/// <seealso cref="Dispose()"/>
public bool IsDisposed
{
get;
private set;
}
#endregion
#region IDisposable Members
/// <summary>
/// Disposes this object instance and all internally managed resources.
/// </summary>
/// <remarks>
/// <para>Sets the <see cref="IsDisposed"/> property to true. Does not explicitly throw an exception if called multiple times, but makes no promises about behaviour of derived classes.</para>
/// </remarks>
/// <seealso cref="IsDisposed"/>
public void Dispose()
{
IsDisposed = true;
Dispose(true);
}
#endregion
}
}

View File

@@ -45,9 +45,4 @@ namespace Emby.Server.Implementations.Net
/// <returns>Task.</returns>
Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken);
}
public interface IMemoryWebSocket
{
Action<Memory<byte>, int> OnReceiveMemoryBytes { get; set; }
}
}

View File

@@ -4,7 +4,6 @@ using System.Net;
using System.Net.Sockets;
using Emby.Server.Implementations.Networking;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Net
{
@@ -19,7 +18,10 @@ namespace Emby.Server.Implementations.Net
public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
{
if (remotePort < 0) throw new ArgumentException("remotePort cannot be less than zero.", nameof(remotePort));
if (remotePort < 0)
{
throw new ArgumentException("remotePort cannot be less than zero.", nameof(remotePort));
}
var addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
? AddressFamily.InterNetwork
@@ -42,8 +44,7 @@ namespace Emby.Server.Implementations.Net
}
catch
{
if (retVal != null)
retVal.Dispose();
retVal?.Dispose();
throw;
}
@@ -55,7 +56,10 @@ namespace Emby.Server.Implementations.Net
/// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
public ISocket CreateUdpSocket(int localPort)
{
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
if (localPort < 0)
{
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
try
@@ -65,8 +69,7 @@ namespace Emby.Server.Implementations.Net
}
catch
{
if (retVal != null)
retVal.Dispose();
retVal?.Dispose();
throw;
}
@@ -74,7 +77,10 @@ namespace Emby.Server.Implementations.Net
public ISocket CreateUdpBroadcastSocket(int localPort)
{
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
if (localPort < 0)
{
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
try
@@ -86,8 +92,7 @@ namespace Emby.Server.Implementations.Net
}
catch
{
if (retVal != null)
retVal.Dispose();
retVal?.Dispose();
throw;
}
@@ -99,7 +104,10 @@ namespace Emby.Server.Implementations.Net
/// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
{
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
if (localPort < 0)
{
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
try
@@ -114,8 +122,7 @@ namespace Emby.Server.Implementations.Net
}
catch
{
if (retVal != null)
retVal.Dispose();
retVal?.Dispose();
throw;
}
@@ -130,10 +137,25 @@ namespace Emby.Server.Implementations.Net
/// <returns></returns>
public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
{
if (ipAddress == null) throw new ArgumentNullException(nameof(ipAddress));
if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
if (ipAddress == null)
{
throw new ArgumentNullException(nameof(ipAddress));
}
if (ipAddress.Length == 0)
{
throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
}
if (multicastTimeToLive <= 0)
{
throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
}
if (localPort < 0)
{
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
@@ -172,87 +194,13 @@ namespace Emby.Server.Implementations.Net
}
catch
{
if (retVal != null)
retVal.Dispose();
retVal?.Dispose();
throw;
}
}
public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
{
var netSocket = (UdpSocket)socket;
return new SocketStream(netSocket.Socket, ownsSocket);
}
=> new NetworkStream(((UdpSocket)socket).Socket, ownsSocket);
}
public class SocketStream : Stream
{
private readonly Socket _socket;
public SocketStream(Socket socket, bool ownsSocket)
{
_socket = socket;
}
public override void Flush()
{
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotImplementedException();
public override long Position
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
_socket.Send(buffer, offset, count, SocketFlags.None);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
_socket.EndSend(asyncResult);
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _socket.Receive(buffer, offset, count, SocketFlags.None);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
return _socket.EndReceive(asyncResult);
}
}
}

View File

@@ -11,12 +11,15 @@ namespace Emby.Server.Implementations.Net
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
// Be careful to check any changes compile and work for all platform projects it is shared in.
public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
public sealed class UdpSocket : ISocket, IDisposable
{
private Socket _Socket;
private int _LocalPort;
private Socket _socket;
private int _localPort;
private bool _disposed = false;
public Socket Socket => _Socket;
public Socket Socket => _socket;
public IpAddressInfo LocalIPAddress { get; }
private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
{
@@ -35,11 +38,11 @@ namespace Emby.Server.Implementations.Net
{
if (socket == null) throw new ArgumentNullException(nameof(socket));
_Socket = socket;
_LocalPort = localPort;
_socket = socket;
_localPort = localPort;
LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
_Socket.Bind(new IPEndPoint(ip, _LocalPort));
_socket.Bind(new IPEndPoint(ip, _localPort));
InitReceiveSocketAsyncEventArgs();
}
@@ -101,32 +104,26 @@ namespace Emby.Server.Implementations.Net
{
if (socket == null) throw new ArgumentNullException(nameof(socket));
_Socket = socket;
_Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
_socket = socket;
_socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
InitReceiveSocketAsyncEventArgs();
}
public IpAddressInfo LocalIPAddress
{
get;
private set;
}
public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
{
ThrowIfDisposed();
EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
}
public int Receive(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
return _Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
}
public SocketReceiveResult EndReceive(IAsyncResult result)
@@ -136,7 +133,7 @@ namespace Emby.Server.Implementations.Net
var sender = new IPEndPoint(IPAddress.Any, 0);
var remoteEndPoint = (EndPoint)sender;
var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
var buffer = (byte[])result.AsyncState;
@@ -236,37 +233,42 @@ namespace Emby.Server.Implementations.Net
var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
}
public int EndSendTo(IAsyncResult result)
{
ThrowIfDisposed();
return _Socket.EndSendTo(result);
return _socket.EndSendTo(result);
}
protected override void Dispose(bool disposing)
private void ThrowIfDisposed()
{
if (disposing)
if (_disposed)
{
var socket = _Socket;
if (socket != null)
socket.Dispose();
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
tcs.TrySetCanceled();
}
var sendTcs = _currentSendTaskCompletionSource;
if (sendTcs != null)
{
sendTcs.TrySetCanceled();
}
throw new ObjectDisposedException(nameof(UdpSocket));
}
}
public void Dispose()
{
if (_disposed)
{
return;
}
_socket?.Dispose();
_currentReceiveTaskCompletionSource?.TrySetCanceled();
_currentSendTaskCompletionSource?.TrySetCanceled();
_socket = null;
_currentReceiveTaskCompletionSource = null;
_currentSendTaskCompletionSource = null;
_disposed = true;
}
private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
{
if (endpoint == null)

View File

@@ -1,5 +1,7 @@
using System;
using System.Net.WebSockets;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
namespace Emby.Server.Implementations.Net
{
@@ -14,7 +16,7 @@ namespace Emby.Server.Implementations.Net
/// Gets or sets the query string.
/// </summary>
/// <value>The query string.</value>
public QueryParamCollection QueryString { get; set; }
public IQueryCollection QueryString { get; set; }
/// <summary>
/// Gets or sets the web socket.
/// </summary>

View File

@@ -7,11 +7,11 @@ using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.System;
using Microsoft.Extensions.Logging;
using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
namespace Emby.Server.Implementations.Networking
{
@@ -22,14 +22,12 @@ namespace Emby.Server.Implementations.Networking
public event EventHandler NetworkChanged;
public Func<string[]> LocalSubnetsFn { get; set; }
public NetworkManager(
ILoggerFactory loggerFactory,
IEnvironmentInfo environment)
public NetworkManager(ILoggerFactory loggerFactory)
{
Logger = loggerFactory.CreateLogger(nameof(NetworkManager));
// In FreeBSD these events cause a crash
if (environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.BSD)
if (OperatingSystem.Id != OperatingSystemId.BSD)
{
try
{

View File

@@ -24,7 +24,7 @@ namespace Emby.Server.Implementations.Playlists
{
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var playlist = (Playlist)item;
@@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Playlists
_libraryManager = libraryManager;
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return _libraryManager.GetItemList(new InternalItemsQuery
{
@@ -89,7 +89,6 @@ namespace Emby.Server.Implementations.Playlists
Recursive = true,
ImageTypes = new[] { ImageType.Primary },
DtoOptions = new DtoOptions(false)
});
}
}
@@ -103,7 +102,7 @@ namespace Emby.Server.Implementations.Playlists
_libraryManager = libraryManager;
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return _libraryManager.GetItemList(new InternalItemsQuery
{
@@ -116,11 +115,5 @@ namespace Emby.Server.Implementations.Playlists
DtoOptions = new DtoOptions(false)
});
}
//protected override Task<string> CreateImage(IHasMetadata item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
//{
// return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
//}
}
}

View File

@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jellyfin Project")]
[assembly: AssemblyProduct("Jellyfin Server")]
[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License Version 2")]
[assembly: AssemblyCopyright("Copyright © 2019 Jellyfin Contributors. Code released under the GNU General Public License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

View File

@@ -1,25 +0,0 @@
using System;
using System.IO;
using System.Reflection;
using MediaBrowser.Model.Reflection;
namespace Emby.Server.Implementations.Reflection
{
public class AssemblyInfo : IAssemblyInfo
{
public Stream GetManifestResourceStream(Type type, string resource)
{
return type.Assembly.GetManifestResourceStream(resource);
}
public string[] GetManifestResourceNames(Type type)
{
return type.Assembly.GetManifestResourceNames();
}
public Assembly[] GetCurrentAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies();
}
}
}

View File

@@ -17,11 +17,13 @@ namespace Emby.Server.Implementations
string programDataPath,
string logDirectoryPath,
string configurationDirectoryPath,
string cacheDirectoryPath)
string cacheDirectoryPath,
string webDirectoryPath)
: base(programDataPath,
logDirectoryPath,
configurationDirectoryPath,
cacheDirectoryPath)
cacheDirectoryPath,
webDirectoryPath)
{
}

View File

@@ -43,14 +43,9 @@ namespace Emby.Server.Implementations.Services
{
var contentLength = bytesResponse.Length;
if (response != null)
{
response.SetContentLength(contentLength);
}
if (contentLength > 0)
{
await responseStream.WriteAsync(bytesResponse, 0, contentLength).ConfigureAwait(false);
await responseStream.WriteAsync(bytesResponse, 0, contentLength, cancellationToken).ConfigureAwait(false);
}
return;
}

View File

@@ -20,8 +20,6 @@ namespace Emby.Server.Implementations.Services
{
response.StatusCode = (int)HttpStatusCode.NoContent;
}
response.SetContentLength(0);
return Task.CompletedTask;
}
@@ -55,7 +53,6 @@ namespace Emby.Server.Implementations.Services
{
if (string.Equals(responseHeaders.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
{
response.SetContentLength(long.Parse(responseHeaders.Value));
continue;
}
@@ -104,7 +101,6 @@ namespace Emby.Server.Implementations.Services
if (bytes != null)
{
response.ContentType = "application/octet-stream";
response.SetContentLength(bytes.Length);
if (bytes.Length > 0)
{
@@ -117,7 +113,6 @@ namespace Emby.Server.Implementations.Services
if (responseText != null)
{
bytes = Encoding.UTF8.GetBytes(responseText);
response.SetContentLength(bytes.Length);
if (bytes.Length > 0)
{
return response.OutputStream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
@@ -149,8 +144,6 @@ namespace Emby.Server.Implementations.Services
var contentLength = ms.Length;
response.SetContentLength(contentLength);
if (contentLength > 0)
{
await ms.CopyToAsync(response.OutputStream).ConfigureAwait(false);

View File

@@ -78,7 +78,7 @@ namespace Emby.Server.Implementations.Services
foreach (var requestFilter in actionContext.RequestFilters)
{
requestFilter.RequestFilter(request, request.Response, requestDto);
if (request.Response.IsClosed)
if (request.Response.OriginalResponse.HasStarted)
{
Task.FromResult<object>(null);
}

View File

@@ -154,7 +154,7 @@ namespace Emby.Server.Implementations.Services
{
if (name == null) continue; //thank you ASP.NET
var values = request.QueryString.GetValues(name);
var values = request.QueryString[name];
if (values.Count == 1)
{
map[name] = values[0];

View File

@@ -116,14 +116,14 @@ namespace Emby.Server.Implementations.Session
_authRepo = authRepo;
_deviceManager = deviceManager;
_mediaSourceManager = mediaSourceManager;
_deviceManager.DeviceOptionsUpdated += _deviceManager_DeviceOptionsUpdated;
_deviceManager.DeviceOptionsUpdated += OnDeviceManagerDeviceOptionsUpdated;
}
private void _deviceManager_DeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
private void OnDeviceManagerDeviceOptionsUpdated(object sender, GenericEventArgs<Tuple<string, DeviceOptions>> e)
{
foreach (var session in Sessions)
{
if (string.Equals(session.DeviceId, e.Argument.Item1))
if (string.Equals(session.DeviceId, e.Argument.Item1, StringComparison.Ordinal))
{
if (!string.IsNullOrWhiteSpace(e.Argument.Item2.CustomName))
{
@@ -138,11 +138,29 @@ namespace Emby.Server.Implementations.Session
}
}
private bool _disposed;
private bool _disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
// TODO: dispose stuff
}
_deviceManager.DeviceOptionsUpdated -= OnDeviceManagerDeviceOptionsUpdated;
_disposed = true;
_deviceManager.DeviceOptionsUpdated -= _deviceManager_DeviceOptionsUpdated;
}
public void CheckDisposed()
@@ -157,7 +175,7 @@ namespace Emby.Server.Implementations.Session
/// Gets all connections.
/// </summary>
/// <value>All connections.</value>
public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate).ToList();
public IEnumerable<SessionInfo> Sessions => _activeConnections.Values.OrderByDescending(c => c.LastActivityDate);
private void OnSessionStarted(SessionInfo info)
{
@@ -171,20 +189,27 @@ namespace Emby.Server.Implementations.Session
}
}
EventHelper.QueueEventIfNotNull(SessionStarted, this, new SessionEventArgs
{
SessionInfo = info
}, _logger);
EventHelper.QueueEventIfNotNull(
SessionStarted,
this,
new SessionEventArgs
{
SessionInfo = info
},
_logger);
}
private void OnSessionEnded(SessionInfo info)
{
EventHelper.QueueEventIfNotNull(SessionEnded, this, new SessionEventArgs
{
SessionInfo = info
EventHelper.QueueEventIfNotNull(
SessionEnded,
this,
new SessionEventArgs
{
SessionInfo = info
}, _logger);
},
_logger);
info.Dispose();
}
@@ -192,9 +217,6 @@ namespace Emby.Server.Implementations.Session
public void UpdateDeviceName(string sessionId, string deviceName)
{
var session = GetSession(sessionId);
var key = GetSessionKey(session.Client, session.DeviceId);
if (session != null)
{
session.DeviceName = deviceName;
@@ -210,10 +232,10 @@ namespace Emby.Server.Implementations.Session
/// <param name="deviceName">Name of the device.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="user">The user.</param>
/// <returns>Task.</returns>
/// <returns>SessionInfo.</returns>
/// <exception cref="ArgumentNullException">user</exception>
/// <exception cref="UnauthorizedAccessException"></exception>
public SessionInfo LogSessionActivity(string appName,
public SessionInfo LogSessionActivity(
string appName,
string appVersion,
string deviceId,
string deviceName,
@@ -226,10 +248,12 @@ namespace Emby.Server.Implementations.Session
{
throw new ArgumentNullException(nameof(appName));
}
if (string.IsNullOrEmpty(appVersion))
{
throw new ArgumentNullException(nameof(appVersion));
}
if (string.IsNullOrEmpty(deviceId))
{
throw new ArgumentNullException(nameof(deviceId));
@@ -260,10 +284,12 @@ namespace Emby.Server.Implementations.Session
if ((activityDate - lastActivityDate).TotalSeconds > 10)
{
SessionActivity?.Invoke(this, new SessionEventArgs
{
SessionInfo = session
});
SessionActivity?.Invoke(
this,
new SessionEventArgs
{
SessionInfo = session
});
}
return session;
@@ -304,6 +330,7 @@ namespace Emby.Server.Implementations.Session
/// <summary>
/// Updates the now playing item id.
/// </summary>
/// <returns>Task.</returns>
private async Task UpdateNowPlayingItem(SessionInfo session, PlaybackProgressInfo info, BaseItem libraryItem, bool updateLastCheckInTime)
{
if (string.IsNullOrEmpty(info.MediaSourceId))
@@ -418,7 +445,7 @@ namespace Emby.Server.Implementations.Session
});
sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
sessionInfo.UserName = user == null ? null : user.Name;
sessionInfo.UserName = user?.Name;
sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
sessionInfo.RemoteEndPoint = remoteEndPoint;
sessionInfo.Client = appName;
@@ -432,7 +459,7 @@ namespace Emby.Server.Implementations.Session
if (user == null)
{
sessionInfo.AdditionalUsers = new SessionUserInfo[] { };
sessionInfo.AdditionalUsers = Array.Empty<SessionUserInfo>();
}
return sessionInfo;
@@ -449,9 +476,9 @@ namespace Emby.Server.Implementations.Session
ServerId = _appHost.SystemId
};
var username = user == null ? null : user.Name;
var username = user?.Name;
sessionInfo.UserId = user == null ? Guid.Empty : user.Id;
sessionInfo.UserId = user?.Id ?? Guid.Empty;
sessionInfo.UserName = username;
sessionInfo.UserPrimaryImageTag = user == null ? null : GetImageCacheTag(user, ImageType.Primary);
sessionInfo.RemoteEndPoint = remoteEndPoint;
@@ -508,6 +535,7 @@ namespace Emby.Server.Implementations.Session
_idleTimer = new Timer(CheckForIdlePlayback, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));
}
}
private void StopIdleCheckTimer()
{
if (_idleTimer != null)
@@ -539,9 +567,9 @@ namespace Emby.Server.Implementations.Session
Item = session.NowPlayingItem,
ItemId = session.NowPlayingItem == null ? Guid.Empty : session.NowPlayingItem.Id,
SessionId = session.Id,
MediaSourceId = session.PlayState == null ? null : session.PlayState.MediaSourceId,
PositionTicks = session.PlayState == null ? null : session.PlayState.PositionTicks
});
MediaSourceId = session.PlayState?.MediaSourceId,
PositionTicks = session.PlayState?.PositionTicks
}).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -616,18 +644,22 @@ namespace Emby.Server.Implementations.Session
// Nothing to save here
// Fire events to inform plugins
EventHelper.QueueEventIfNotNull(PlaybackStart, this, new PlaybackProgressEventArgs
{
Item = libraryItem,
Users = users,
MediaSourceId = info.MediaSourceId,
MediaInfo = info.Item,
DeviceName = session.DeviceName,
ClientName = session.Client,
DeviceId = session.DeviceId,
Session = session
EventHelper.QueueEventIfNotNull(
PlaybackStart,
this,
new PlaybackProgressEventArgs
{
Item = libraryItem,
Users = users,
MediaSourceId = info.MediaSourceId,
MediaInfo = info.Item,
DeviceName = session.DeviceName,
ClientName = session.Client,
DeviceId = session.DeviceId,
Session = session
}, _logger);
},
_logger);
StartIdleCheckTimer();
}
@@ -667,6 +699,7 @@ namespace Emby.Server.Implementations.Session
/// <summary>
/// Used to report playback progress for an item
/// </summary>
/// <returns>Task.</returns>
public async Task OnPlaybackProgress(PlaybackProgressInfo info, bool isAutomated)
{
CheckDisposed();
@@ -695,21 +728,23 @@ namespace Emby.Server.Implementations.Session
}
}
PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs
{
Item = libraryItem,
Users = users,
PlaybackPositionTicks = session.PlayState.PositionTicks,
MediaSourceId = session.PlayState.MediaSourceId,
MediaInfo = info.Item,
DeviceName = session.DeviceName,
ClientName = session.Client,
DeviceId = session.DeviceId,
IsPaused = info.IsPaused,
PlaySessionId = info.PlaySessionId,
IsAutomated = isAutomated,
Session = session
});
PlaybackProgress?.Invoke(
this,
new PlaybackProgressEventArgs
{
Item = libraryItem,
Users = users,
PlaybackPositionTicks = session.PlayState.PositionTicks,
MediaSourceId = session.PlayState.MediaSourceId,
MediaInfo = info.Item,
DeviceName = session.DeviceName,
ClientName = session.Client,
DeviceId = session.DeviceId,
IsPaused = info.IsPaused,
PlaySessionId = info.PlaySessionId,
IsAutomated = isAutomated,
Session = session
});
if (!isAutomated)
{
@@ -830,8 +865,7 @@ namespace Emby.Server.Implementations.Session
{
MediaSourceInfo mediaSource = null;
var hasMediaSources = libraryItem as IHasMediaSources;
if (hasMediaSources != null)
if (libraryItem is IHasMediaSources hasMediaSources)
{
mediaSource = await GetMediaSource(libraryItem, info.MediaSourceId, info.LiveStreamId).ConfigureAwait(false);
}
@@ -848,7 +882,8 @@ namespace Emby.Server.Implementations.Session
{
var msString = info.PositionTicks.HasValue ? (info.PositionTicks.Value / 10000).ToString(CultureInfo.InvariantCulture) : "unknown";
_logger.LogInformation("Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
_logger.LogInformation(
"Playback stopped reported by app {0} {1} playing {2}. Stopped at {3} ms",
session.Client,
session.ApplicationVersion,
info.Item.Name,
@@ -887,20 +922,24 @@ namespace Emby.Server.Implementations.Session
}
}
EventHelper.QueueEventIfNotNull(PlaybackStopped, this, new PlaybackStopEventArgs
{
Item = libraryItem,
Users = users,
PlaybackPositionTicks = info.PositionTicks,
PlayedToCompletion = playedToCompletion,
MediaSourceId = info.MediaSourceId,
MediaInfo = info.Item,
DeviceName = session.DeviceName,
ClientName = session.Client,
DeviceId = session.DeviceId,
Session = session
EventHelper.QueueEventIfNotNull(
PlaybackStopped,
this,
new PlaybackStopEventArgs
{
Item = libraryItem,
Users = users,
PlaybackPositionTicks = info.PositionTicks,
PlayedToCompletion = playedToCompletion,
MediaSourceId = info.MediaSourceId,
MediaInfo = info.Item,
DeviceName = session.DeviceName,
ClientName = session.Client,
DeviceId = session.DeviceId,
Session = session
}, _logger);
},
_logger);
}
private bool OnPlaybackStopped(User user, BaseItem item, long? positionTicks, bool playbackFailed)
@@ -936,11 +975,10 @@ namespace Emby.Server.Implementations.Session
/// <param name="sessionId">The session identifier.</param>
/// <param name="throwOnMissing">if set to <c>true</c> [throw on missing].</param>
/// <returns>SessionInfo.</returns>
/// <exception cref="ResourceNotFoundException"></exception>
/// <exception cref="ResourceNotFoundException">sessionId</exception>
private SessionInfo GetSession(string sessionId, bool throwOnMissing = true)
{
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
if (session == null && throwOnMissing)
{
throw new ResourceNotFoundException(string.Format("Session {0} not found.", sessionId));
@@ -952,7 +990,7 @@ namespace Emby.Server.Implementations.Session
private SessionInfo GetSessionToRemoteControl(string sessionId)
{
// Accept either device id or session id
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId));
var session = Sessions.FirstOrDefault(i => string.Equals(i.Id, sessionId, StringComparison.Ordinal));
if (session == null)
{
@@ -1061,10 +1099,12 @@ namespace Emby.Server.Implementations.Session
var series = episode.Series;
if (series != null)
{
var episodes = series.GetEpisodes(user, new DtoOptions(false)
{
EnableImages = false
})
var episodes = series.GetEpisodes(
user,
new DtoOptions(false)
{
EnableImages = false
})
.Where(i => !i.IsVirtualItem)
.SkipWhile(i => i.Id != episode.Id)
.ToList();
@@ -1100,9 +1140,7 @@ namespace Emby.Server.Implementations.Session
return new List<BaseItem>();
}
var byName = item as IItemByName;
if (byName != null)
if (item is IItemByName byName)
{
return byName.GetTaggedItems(new InternalItemsQuery(user)
{
@@ -1152,7 +1190,7 @@ namespace Emby.Server.Implementations.Session
if (item == null)
{
_logger.LogError("A non-existant item Id {0} was passed into TranslateItemForInstantMix", id);
_logger.LogError("A non-existent item Id {0} was passed into TranslateItemForInstantMix", id);
return new List<BaseItem>();
}
@@ -1163,13 +1201,15 @@ namespace Emby.Server.Implementations.Session
{
var generalCommand = new GeneralCommand
{
Name = GeneralCommandType.DisplayContent.ToString()
Name = GeneralCommandType.DisplayContent.ToString(),
Arguments =
{
["ItemId"] = command.ItemId,
["ItemName"] = command.ItemName,
["ItemType"] = command.ItemType
}
};
generalCommand.Arguments["ItemId"] = command.ItemId;
generalCommand.Arguments["ItemName"] = command.ItemName;
generalCommand.Arguments["ItemType"] = command.ItemType;
return SendGeneralCommand(controllingSessionId, sessionId, generalCommand, cancellationToken);
}
@@ -1410,7 +1450,8 @@ namespace Emby.Server.Implementations.Session
var token = GetAuthorizationToken(user, request.DeviceId, request.App, request.AppVersion, request.DeviceName);
var session = LogSessionActivity(request.App,
var session = LogSessionActivity(
request.App,
request.AppVersion,
request.DeviceId,
request.DeviceName,
@@ -1454,9 +1495,9 @@ namespace Emby.Server.Implementations.Session
{
Logout(auth);
}
catch
catch (Exception ex)
{
_logger.LogError(ex, "Error while logging out.");
}
}
}
@@ -1572,7 +1613,8 @@ namespace Emby.Server.Implementations.Session
ReportCapabilities(session, capabilities, true);
}
private void ReportCapabilities(SessionInfo session,
private void ReportCapabilities(
SessionInfo session,
ClientCapabilities capabilities,
bool saveCapabilities)
{
@@ -1580,10 +1622,12 @@ namespace Emby.Server.Implementations.Session
if (saveCapabilities)
{
CapabilitiesChanged?.Invoke(this, new SessionEventArgs
{
SessionInfo = session
});
CapabilitiesChanged?.Invoke(
this,
new SessionEventArgs
{
SessionInfo = session
});
try
{

View File

@@ -5,6 +5,7 @@ using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.Session
@@ -62,7 +63,7 @@ namespace Emby.Server.Implementations.Session
}
}
private SessionInfo GetSession(QueryParamCollection queryString, string remoteEndpoint)
private SessionInfo GetSession(IQueryCollection queryString, string remoteEndpoint)
{
if (queryString == null)
{

View File

@@ -0,0 +1,18 @@
using System.IO;
using MediaBrowser.Model.Services;
namespace Emby.Server.Implementations.SocketSharp
{
public class HttpFile : IHttpFile
{
public string Name { get; set; }
public string FileName { get; set; }
public long ContentLength { get; set; }
public string ContentType { get; set; }
public Stream InputStream { get; set; }
}
}

View File

@@ -0,0 +1,204 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
public sealed class HttpPostedFile : IDisposable
{
private string _name;
private string _contentType;
private Stream _stream;
private bool _disposed = false;
internal HttpPostedFile(string name, string content_type, Stream base_stream, long offset, long length)
{
_name = name;
_contentType = content_type;
_stream = new ReadSubStream(base_stream, offset, length);
}
public string ContentType => _contentType;
public int ContentLength => (int)_stream.Length;
public string FileName => _name;
public Stream InputStream => _stream;
/// <summary>
/// Releases the unmanaged resources and disposes of the managed resources used.
/// </summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_stream.Dispose();
_stream = null;
_name = null;
_contentType = null;
_disposed = true;
}
private class ReadSubStream : Stream
{
private Stream _stream;
private long _offset;
private long _end;
private long _position;
public ReadSubStream(Stream s, long offset, long length)
{
_stream = s;
_offset = offset;
_end = offset + length;
_position = offset;
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => _end - _offset;
public override long Position
{
get => _position - _offset;
set
{
if (value > Length)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_position = Seek(value, SeekOrigin.Begin);
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int dest_offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (dest_offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(dest_offset), "< 0");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "< 0");
}
int len = buffer.Length;
if (dest_offset > len)
{
throw new ArgumentException("destination offset is beyond array size", nameof(dest_offset));
}
// reordered to avoid possible integer overflow
if (dest_offset > len - count)
{
throw new ArgumentException("Reading would overrun buffer", nameof(count));
}
if (count > _end - _position)
{
count = (int)(_end - _position);
}
if (count <= 0)
{
return 0;
}
_stream.Position = _position;
int result = _stream.Read(buffer, dest_offset, count);
if (result > 0)
{
_position += result;
}
else
{
_position = _end;
}
return result;
}
public override int ReadByte()
{
if (_position >= _end)
{
return -1;
}
_stream.Position = _position;
int result = _stream.ReadByte();
if (result < 0)
{
_position = _end;
}
else
{
_position++;
}
return result;
}
public override long Seek(long d, SeekOrigin origin)
{
long real;
switch (origin)
{
case SeekOrigin.Begin:
real = _offset + d;
break;
case SeekOrigin.End:
real = _end + d;
break;
case SeekOrigin.Current:
real = _position + d;
break;
default:
throw new ArgumentException("Unknown SeekOrigin value", nameof(origin));
}
long virt = real - _offset;
if (virt < 0 || virt > Length)
{
throw new ArgumentException("Invalid position", nameof(d));
}
_position = _stream.Seek(real, SeekOrigin.Begin);
return _position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
}

View File

@@ -0,0 +1,659 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.SocketSharp
{
public partial class WebSocketSharpRequest : IHttpRequest
{
internal static string GetParameter(ReadOnlySpan<char> header, string attr)
{
int ap = header.IndexOf(attr.AsSpan(), StringComparison.Ordinal);
if (ap == -1)
{
return null;
}
ap += attr.Length;
if (ap >= header.Length)
{
return null;
}
char ending = header[ap];
if (ending != '"')
{
ending = ' ';
}
var slice = header.Slice(ap + 1);
int end = slice.IndexOf(ending);
if (end == -1)
{
return ending == '"' ? null : header.Slice(ap).ToString();
}
return slice.Slice(0, end - ap - 1).ToString();
}
private async Task LoadMultiPart(WebROCollection form)
{
string boundary = GetParameter(ContentType.AsSpan(), "; boundary=");
if (boundary == null)
{
return;
}
using (var requestStream = InputStream)
{
// DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
// Not ending with \r\n?
var ms = new MemoryStream(32 * 1024);
await requestStream.CopyToAsync(ms).ConfigureAwait(false);
var input = ms;
ms.WriteByte((byte)'\r');
ms.WriteByte((byte)'\n');
input.Position = 0;
// Uncomment to debug
// var content = new StreamReader(ms).ReadToEnd();
// Console.WriteLine(boundary + "::" + content);
// input.Position = 0;
var multi_part = new HttpMultipart(input, boundary, ContentEncoding);
HttpMultipart.Element e;
while ((e = multi_part.ReadNextElement()) != null)
{
if (e.Filename == null)
{
byte[] copy = new byte[e.Length];
input.Position = e.Start;
await input.ReadAsync(copy, 0, (int)e.Length).ConfigureAwait(false);
form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
}
else
{
// We use a substream, as in 2.x we will support large uploads streamed to disk,
var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
files[e.Name] = sub;
}
}
}
}
public async Task<QueryParamCollection> GetFormData()
{
var form = new WebROCollection();
files = new Dictionary<string, HttpPostedFile>();
if (IsContentType("multipart/form-data"))
{
await LoadMultiPart(form).ConfigureAwait(false);
}
else if (IsContentType("application/x-www-form-urlencoded"))
{
await LoadWwwForm(form).ConfigureAwait(false);
}
if (validate_form && !checked_form)
{
checked_form = true;
ValidateNameValueCollection("Form", form);
}
return form;
}
public string Accept => StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Accept]) ? null : request.Headers[HeaderNames.Accept].ToString();
public string Authorization => StringValues.IsNullOrEmpty(request.Headers[HeaderNames.Authorization]) ? null : request.Headers[HeaderNames.Authorization].ToString();
protected bool validate_form { get; set; }
protected bool checked_form { get; set; }
private static void ThrowValidationException(string name, string key, string value)
{
string v = "\"" + value + "\"";
if (v.Length > 20)
{
v = v.Substring(0, 16) + "...\"";
}
string msg = string.Format(
CultureInfo.InvariantCulture,
"A potentially dangerous Request.{0} value was detected from the client ({1}={2}).",
name,
key,
v);
throw new Exception(msg);
}
private static void ValidateNameValueCollection(string name, QueryParamCollection coll)
{
if (coll == null)
{
return;
}
foreach (var pair in coll)
{
var key = pair.Name;
var val = pair.Value;
if (val != null && val.Length > 0 && IsInvalidString(val))
{
ThrowValidationException(name, key, val);
}
}
}
internal static bool IsInvalidString(string val)
=> IsInvalidString(val, out var validationFailureIndex);
internal static bool IsInvalidString(string val, out int validationFailureIndex)
{
validationFailureIndex = 0;
int len = val.Length;
if (len < 2)
{
return false;
}
char current = val[0];
for (int idx = 1; idx < len; idx++)
{
char next = val[idx];
// See http://secunia.com/advisories/14325
if (current == '<' || current == '\xff1c')
{
if (next == '!' || next < ' '
|| (next >= 'a' && next <= 'z')
|| (next >= 'A' && next <= 'Z'))
{
validationFailureIndex = idx - 1;
return true;
}
}
else if (current == '&' && next == '#')
{
validationFailureIndex = idx - 1;
return true;
}
current = next;
}
return false;
}
private bool IsContentType(string ct)
{
if (ContentType == null)
{
return false;
}
return ContentType.StartsWith(ct, StringComparison.OrdinalIgnoreCase);
}
private async Task LoadWwwForm(WebROCollection form)
{
using (var input = InputStream)
{
using (var ms = new MemoryStream())
{
await input.CopyToAsync(ms).ConfigureAwait(false);
ms.Position = 0;
using (var s = new StreamReader(ms, ContentEncoding))
{
var key = new StringBuilder();
var value = new StringBuilder();
int c;
while ((c = s.Read()) != -1)
{
if (c == '=')
{
value.Length = 0;
while ((c = s.Read()) != -1)
{
if (c == '&')
{
AddRawKeyValue(form, key, value);
break;
}
else
{
value.Append((char)c);
}
}
if (c == -1)
{
AddRawKeyValue(form, key, value);
return;
}
}
else if (c == '&')
{
AddRawKeyValue(form, key, value);
}
else
{
key.Append((char)c);
}
}
if (c == -1)
{
AddRawKeyValue(form, key, value);
}
}
}
}
}
private static void AddRawKeyValue(WebROCollection form, StringBuilder key, StringBuilder value)
{
form.Add(WebUtility.UrlDecode(key.ToString()), WebUtility.UrlDecode(value.ToString()));
key.Length = 0;
value.Length = 0;
}
private Dictionary<string, HttpPostedFile> files;
private class WebROCollection : QueryParamCollection
{
public override string ToString()
{
var result = new StringBuilder();
foreach (var pair in this)
{
if (result.Length > 0)
{
result.Append('&');
}
var key = pair.Name;
if (key != null && key.Length > 0)
{
result.Append(key);
result.Append('=');
}
result.Append(pair.Value);
}
return result.ToString();
}
}
private class HttpMultipart
{
public class Element
{
public string ContentType { get; set; }
public string Name { get; set; }
public string Filename { get; set; }
public Encoding Encoding { get; set; }
public long Start { get; set; }
public long Length { get; set; }
public override string ToString()
{
return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
Start.ToString(CultureInfo.CurrentCulture) + ", Length " + Length.ToString(CultureInfo.CurrentCulture);
}
}
private const byte LF = (byte)'\n';
private const byte CR = (byte)'\r';
private Stream data;
private string boundary;
private byte[] boundaryBytes;
private byte[] buffer;
private bool atEof;
private Encoding encoding;
private StringBuilder sb;
// See RFC 2046
// In the case of multipart entities, in which one or more different
// sets of data are combined in a single body, a "multipart" media type
// field must appear in the entity's header. The body must then contain
// one or more body parts, each preceded by a boundary delimiter line,
// and the last one followed by a closing boundary delimiter line.
// After its boundary delimiter line, each body part then consists of a
// header area, a blank line, and a body area. Thus a body part is
// similar to an RFC 822 message in syntax, but different in meaning.
public HttpMultipart(Stream data, string b, Encoding encoding)
{
this.data = data;
boundary = b;
boundaryBytes = encoding.GetBytes(b);
buffer = new byte[boundaryBytes.Length + 2]; // CRLF or '--'
this.encoding = encoding;
sb = new StringBuilder();
}
public Element ReadNextElement()
{
if (atEof || ReadBoundary())
{
return null;
}
var elem = new Element();
ReadOnlySpan<char> header;
while ((header = ReadHeaders().AsSpan()) != null)
{
if (header.StartsWith("Content-Disposition:".AsSpan(), StringComparison.OrdinalIgnoreCase))
{
elem.Name = GetContentDispositionAttribute(header, "name");
elem.Filename = StripPath(GetContentDispositionAttributeWithEncoding(header, "filename"));
}
else if (header.StartsWith("Content-Type:".AsSpan(), StringComparison.OrdinalIgnoreCase))
{
elem.ContentType = header.Slice("Content-Type:".Length).Trim().ToString();
elem.Encoding = GetEncoding(elem.ContentType);
}
}
long start = data.Position;
elem.Start = start;
long pos = MoveToNextBoundary();
if (pos == -1)
{
return null;
}
elem.Length = pos - start;
return elem;
}
private string ReadLine()
{
// CRLF or LF are ok as line endings.
bool got_cr = false;
int b = 0;
sb.Length = 0;
while (true)
{
b = data.ReadByte();
if (b == -1)
{
return null;
}
if (b == LF)
{
break;
}
got_cr = b == CR;
sb.Append((char)b);
}
if (got_cr)
{
sb.Length--;
}
return sb.ToString();
}
private static string GetContentDispositionAttribute(ReadOnlySpan<char> l, string name)
{
int idx = l.IndexOf((name + "=\"").AsSpan(), StringComparison.Ordinal);
if (idx < 0)
{
return null;
}
int begin = idx + name.Length + "=\"".Length;
int end = l.Slice(begin).IndexOf('"');
if (end < 0)
{
return null;
}
if (begin == end)
{
return string.Empty;
}
return l.Slice(begin, end - begin).ToString();
}
private string GetContentDispositionAttributeWithEncoding(ReadOnlySpan<char> l, string name)
{
int idx = l.IndexOf((name + "=\"").AsSpan(), StringComparison.Ordinal);
if (idx < 0)
{
return null;
}
int begin = idx + name.Length + "=\"".Length;
int end = l.Slice(begin).IndexOf('"');
if (end < 0)
{
return null;
}
if (begin == end)
{
return string.Empty;
}
ReadOnlySpan<char> temp = l.Slice(begin, end - begin);
byte[] source = new byte[temp.Length];
for (int i = temp.Length - 1; i >= 0; i--)
{
source[i] = (byte)temp[i];
}
return encoding.GetString(source, 0, source.Length);
}
private bool ReadBoundary()
{
try
{
string line;
do
{
line = ReadLine();
}
while (line.Length == 0);
if (line[0] != '-' || line[1] != '-')
{
return false;
}
if (!line.EndsWith(boundary, StringComparison.Ordinal))
{
return true;
}
}
catch
{
}
return false;
}
private string ReadHeaders()
{
string s = ReadLine();
if (s.Length == 0)
{
return null;
}
return s;
}
private static bool CompareBytes(byte[] orig, byte[] other)
{
for (int i = orig.Length - 1; i >= 0; i--)
{
if (orig[i] != other[i])
{
return false;
}
}
return true;
}
private long MoveToNextBoundary()
{
long retval = 0;
bool got_cr = false;
int state = 0;
int c = data.ReadByte();
while (true)
{
if (c == -1)
{
return -1;
}
if (state == 0 && c == LF)
{
retval = data.Position - 1;
if (got_cr)
{
retval--;
}
state = 1;
c = data.ReadByte();
}
else if (state == 0)
{
got_cr = c == CR;
c = data.ReadByte();
}
else if (state == 1 && c == '-')
{
c = data.ReadByte();
if (c == -1)
{
return -1;
}
if (c != '-')
{
state = 0;
got_cr = false;
continue; // no ReadByte() here
}
int nread = data.Read(buffer, 0, buffer.Length);
int bl = buffer.Length;
if (nread != bl)
{
return -1;
}
if (!CompareBytes(boundaryBytes, buffer))
{
state = 0;
data.Position = retval + 2;
if (got_cr)
{
data.Position++;
got_cr = false;
}
c = data.ReadByte();
continue;
}
if (buffer[bl - 2] == '-' && buffer[bl - 1] == '-')
{
atEof = true;
}
else if (buffer[bl - 2] != CR || buffer[bl - 1] != LF)
{
state = 0;
data.Position = retval + 2;
if (got_cr)
{
data.Position++;
got_cr = false;
}
c = data.ReadByte();
continue;
}
data.Position = retval + 2;
if (got_cr)
{
data.Position++;
}
break;
}
else
{
// state == 1
state = 0; // no ReadByte() here
}
}
return retval;
}
private static string StripPath(string path)
{
if (path == null || path.Length == 0)
{
return path;
}
if (path.IndexOf(":\\", StringComparison.Ordinal) != 1
&& !path.StartsWith("\\\\", StringComparison.Ordinal))
{
return path;
}
return path.Substring(path.LastIndexOf('\\') + 1);
}
}
}
}

View File

@@ -0,0 +1,105 @@
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Net;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.SocketSharp
{
public class SharpWebSocket : IWebSocket
{
/// <summary>
/// The logger
/// </summary>
private readonly ILogger _logger;
public event EventHandler<EventArgs> Closed;
/// <summary>
/// Gets or sets the web socket.
/// </summary>
/// <value>The web socket.</value>
private readonly WebSocket _webSocket;
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private bool _disposed;
public SharpWebSocket(WebSocket socket, ILogger logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_webSocket = socket ?? throw new ArgumentNullException(nameof(socket));
}
/// <summary>
/// Gets or sets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State => _webSocket.State;
/// <summary>
/// Sends the async.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendAsync(byte[] bytes, bool endOfMessage, CancellationToken cancellationToken)
{
return _webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Binary, endOfMessage, cancellationToken);
}
/// <summary>
/// Sends the asynchronous.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="endOfMessage">if set to <c>true</c> [end of message].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendAsync(string text, bool endOfMessage, CancellationToken cancellationToken)
{
return _webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(text)), WebSocketMessageType.Text, endOfMessage, cancellationToken);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (_disposed)
{
return;
}
if (dispose)
{
_cancellationTokenSource.Cancel();
if (_webSocket.State == WebSocketState.Open)
{
_webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closed by client",
CancellationToken.None);
}
Closed?.Invoke(this, EventArgs.Empty);
}
_disposed = true;
}
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Action<byte[]> OnReceiveBytes { get; set; }
}
}

View File

@@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.HttpServer;
using Emby.Server.Implementations.Net;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Emby.Server.Implementations.SocketSharp
{
public class WebSocketSharpListener : IHttpListener
{
private readonly ILogger _logger;
private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
private CancellationToken _disposeCancellationToken;
public WebSocketSharpListener(
ILogger logger)
{
_logger = logger;
_disposeCancellationToken = _disposeCancellationTokenSource.Token;
}
public Func<Exception, IRequest, bool, bool, Task> ErrorHandler { get; set; }
public Func<IHttpRequest, string, string, string, CancellationToken, Task> RequestHandler { get; set; }
public Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
private static void LogRequest(ILogger logger, HttpRequest request)
{
var url = request.GetDisplayUrl();
logger.LogInformation("WS {Url}. UserAgent: {UserAgent}", url, request.Headers[HeaderNames.UserAgent].ToString());
}
public async Task ProcessWebSocketRequest(HttpContext ctx)
{
try
{
LogRequest(_logger, ctx.Request);
var endpoint = ctx.Connection.RemoteIpAddress.ToString();
var url = ctx.Request.GetDisplayUrl();
var webSocketContext = await ctx.WebSockets.AcceptWebSocketAsync(null).ConfigureAwait(false);
var socket = new SharpWebSocket(webSocketContext, _logger);
WebSocketConnected(new WebSocketConnectEventArgs
{
Url = url,
QueryString = ctx.Request.Query,
WebSocket = socket,
Endpoint = endpoint
});
WebSocketReceiveResult result;
var message = new List<byte>();
do
{
var buffer = WebSocket.CreateServerBuffer(4096);
result = await webSocketContext.ReceiveAsync(buffer, _disposeCancellationToken);
message.AddRange(buffer.Array.Take(result.Count));
if (result.EndOfMessage)
{
socket.OnReceiveBytes(message.ToArray());
message.Clear();
}
} while (socket.State == WebSocketState.Open && result.MessageType != WebSocketMessageType.Close);
if (webSocketContext.State == WebSocketState.Open)
{
await webSocketContext.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
result.CloseStatusDescription, _disposeCancellationToken);
}
socket.Dispose();
}
catch (Exception ex)
{
_logger.LogError(ex, "AcceptWebSocketAsync error");
if (!ctx.Response.HasStarted)
{
ctx.Response.StatusCode = 500;
}
}
}
public Task Stop()
{
_disposeCancellationTokenSource.Cancel();
return Task.CompletedTask;
}
/// <summary>
/// Releases the unmanaged resources and disposes of the managed resources used.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
/// <summary>
/// Releases the unmanaged resources and disposes of the managed resources used.
/// </summary>
/// <param name="disposing">Whether or not the managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
Stop().GetAwaiter().GetResult();
}
_disposed = true;
}
}
}

View File

@@ -0,0 +1,518 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
using IResponse = MediaBrowser.Model.Services.IResponse;
namespace Emby.Server.Implementations.SocketSharp
{
public partial class WebSocketSharpRequest : IHttpRequest
{
private readonly HttpRequest request;
public WebSocketSharpRequest(HttpRequest httpContext, HttpResponse response, string operationName, ILogger logger)
{
this.OperationName = operationName;
this.request = httpContext;
this.Response = new WebSocketSharpResponse(logger, response);
// HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
}
public HttpRequest HttpRequest => request;
public IResponse Response { get; }
public string OperationName { get; set; }
public object Dto { get; set; }
public string RawUrl => request.GetEncodedPathAndQuery();
public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');
public string XForwardedFor
=> StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"].ToString();
public int? XForwardedPort
=> StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
public string XForwardedProtocol => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"].ToString();
public string XRealIp => StringValues.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"].ToString();
private string remoteIp;
public string RemoteIp
{
get
{
if (remoteIp != null)
{
return remoteIp;
}
var temp = CheckBadChars(XForwardedFor.AsSpan());
if (temp.Length != 0)
{
return remoteIp = temp.ToString();
}
temp = CheckBadChars(XRealIp.AsSpan());
if (temp.Length != 0)
{
return remoteIp = NormalizeIp(temp).ToString();
}
return remoteIp = NormalizeIp(request.HttpContext.Connection.RemoteIpAddress.ToString().AsSpan()).ToString();
}
}
private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
// CheckBadChars - throws on invalid chars to be not found in header name/value
internal static ReadOnlySpan<char> CheckBadChars(ReadOnlySpan<char> name)
{
if (name.Length == 0)
{
return name;
}
// VALUE check
// Trim spaces from both ends
name = name.Trim(HttpTrimCharacters);
// First, check for correctly formed multi-line value
// Second, check for absence of CTL characters
int crlf = 0;
for (int i = 0; i < name.Length; ++i)
{
char c = (char)(0x000000ff & (uint)name[i]);
switch (crlf)
{
case 0:
{
if (c == '\r')
{
crlf = 1;
}
else if (c == '\n')
{
// Technically this is bad HTTP. But it would be a breaking change to throw here.
// Is there an exploit?
crlf = 2;
}
else if (c == 127 || (c < ' ' && c != '\t'))
{
throw new ArgumentException("net_WebHeaderInvalidControlChars", nameof(name));
}
break;
}
case 1:
{
if (c == '\n')
{
crlf = 2;
break;
}
throw new ArgumentException("net_WebHeaderInvalidCRLFChars", nameof(name));
}
case 2:
{
if (c == ' ' || c == '\t')
{
crlf = 0;
break;
}
throw new ArgumentException("net_WebHeaderInvalidCRLFChars", nameof(name));
}
}
}
if (crlf != 0)
{
throw new ArgumentException("net_WebHeaderInvalidCRLFChars", nameof(name));
}
return name;
}
private ReadOnlySpan<char> NormalizeIp(ReadOnlySpan<char> ip)
{
if (ip.Length != 0 && !ip.IsWhiteSpace())
{
// Handle ipv4 mapped to ipv6
const string srch = "::ffff:";
var index = ip.IndexOf(srch.AsSpan(), StringComparison.OrdinalIgnoreCase);
if (index == 0)
{
ip = ip.Slice(srch.Length);
}
}
return ip;
}
public string[] AcceptTypes => request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
private Dictionary<string, object> items;
public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
private string responseContentType;
public string ResponseContentType
{
get =>
responseContentType
?? (responseContentType = GetResponseContentType(HttpRequest));
set => this.responseContentType = value;
}
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
public const string MultiPartFormData = "multipart/form-data";
public static string GetResponseContentType(HttpRequest httpReq)
{
var specifiedContentType = GetQueryStringContentType(httpReq);
if (!string.IsNullOrEmpty(specifiedContentType))
{
return specifiedContentType;
}
const string serverDefaultContentType = "application/json";
var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
string defaultContentType = null;
if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
{
defaultContentType = serverDefaultContentType;
}
var acceptsAnything = false;
var hasDefaultContentType = defaultContentType != null;
if (acceptContentTypes != null)
{
foreach (var acceptsType in acceptContentTypes)
{
// TODO: @bond move to Span when Span.Split lands
// https://github.com/dotnet/corefx/issues/26528
var contentType = acceptsType?.Split(';')[0].Trim();
acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
if (acceptsAnything)
{
break;
}
}
if (acceptsAnything)
{
if (hasDefaultContentType)
{
return defaultContentType;
}
else
{
return serverDefaultContentType;
}
}
}
if (acceptContentTypes == null && httpReq.ContentType == Soap11)
{
return Soap11;
}
// We could also send a '406 Not Acceptable', but this is allowed also
return serverDefaultContentType;
}
public const string Soap11 = "text/xml; charset=utf-8";
public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
{
if (contentTypes == null || request.ContentType == null)
{
return false;
}
foreach (var contentType in contentTypes)
{
if (IsContentType(request, contentType))
{
return true;
}
}
return false;
}
public static bool IsContentType(HttpRequest request, string contentType)
{
return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
}
private static string GetQueryStringContentType(HttpRequest httpReq)
{
ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
if (format == null)
{
const int formatMaxLength = 4;
ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
if (pi == null || pi.Length <= formatMaxLength)
{
return null;
}
if (pi[0] == '/')
{
pi = pi.Slice(1);
}
format = LeftPart(pi, '/');
if (format.Length > formatMaxLength)
{
return null;
}
}
format = LeftPart(format, '.');
if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
{
return "application/json";
}
else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
{
return "application/xml";
}
return null;
}
public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
{
if (strVal == null)
{
return null;
}
var pos = strVal.IndexOf(needle);
return pos == -1 ? strVal : strVal.Slice(0, pos);
}
public static string HandlerFactoryPath;
private string pathInfo;
public string PathInfo
{
get
{
if (this.pathInfo == null)
{
var mode = HandlerFactoryPath;
var pos = RawUrl.IndexOf("?", StringComparison.Ordinal);
if (pos != -1)
{
var path = RawUrl.Substring(0, pos);
this.pathInfo = GetPathInfo(
path,
mode,
mode ?? string.Empty);
}
else
{
this.pathInfo = RawUrl;
}
this.pathInfo = WebUtility.UrlDecode(pathInfo);
this.pathInfo = NormalizePathInfo(pathInfo, mode).ToString();
}
return this.pathInfo;
}
}
private static string GetPathInfo(string fullPath, string mode, string appPath)
{
var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
if (!string.IsNullOrEmpty(pathInfo))
{
return pathInfo;
}
// Wildcard mode relies on this to work out the handlerPath
pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
if (!string.IsNullOrEmpty(pathInfo))
{
return pathInfo;
}
return fullPath;
}
private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
{
if (mappedPathRoot == null)
{
return null;
}
var sbPathInfo = new StringBuilder();
var fullPathParts = fullPath.Split('/');
var mappedPathRootParts = mappedPathRoot.Split('/');
var fullPathIndexOffset = mappedPathRootParts.Length - 1;
var pathRootFound = false;
for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
{
if (pathRootFound)
{
sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
}
else if (fullPathIndex - fullPathIndexOffset >= 0)
{
pathRootFound = true;
for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
{
if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
{
pathRootFound = false;
break;
}
}
}
}
if (!pathRootFound)
{
return null;
}
return sbPathInfo.Length > 1 ? sbPathInfo.ToString().TrimEnd('/') : "/";
}
public string UserAgent => request.Headers[HeaderNames.UserAgent];
public IHeaderDictionary Headers => request.Headers;
public IQueryCollection QueryString => request.Query;
public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
private string httpMethod;
public string HttpMethod =>
httpMethod
?? (httpMethod = request.Method);
public string Verb => HttpMethod;
public string ContentType => request.ContentType;
private Encoding ContentEncoding
{
get
{
// TODO is this necessary?
if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
{
string postDataCharset = Headers["x-up-devcap-post-charset"];
if (!string.IsNullOrEmpty(postDataCharset))
{
try
{
return Encoding.GetEncoding(postDataCharset);
}
catch (ArgumentException)
{
}
}
}
return request.GetTypedHeaders().ContentType.Encoding ?? Encoding.UTF8;
}
}
public Uri UrlReferrer => request.GetTypedHeaders().Referer;
public static Encoding GetEncoding(string contentTypeHeader)
{
var param = GetParameter(contentTypeHeader.AsSpan(), "charset=");
if (param == null)
{
return null;
}
try
{
return Encoding.GetEncoding(param);
}
catch (ArgumentException)
{
return null;
}
}
public Stream InputStream => request.Body;
public long ContentLength => request.ContentLength ?? 0;
private IHttpFile[] httpFiles;
public IHttpFile[] Files
{
get
{
if (httpFiles == null)
{
if (files == null)
{
return httpFiles = Array.Empty<IHttpFile>();
}
httpFiles = new IHttpFile[files.Count];
var i = 0;
foreach (var pair in files)
{
var reqFile = pair.Value;
httpFiles[i] = new HttpFile
{
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
i++;
}
}
return httpFiles;
}
}
public static ReadOnlySpan<char> NormalizePathInfo(string pathInfo, string handlerPath)
{
if (handlerPath != null)
{
var trimmed = pathInfo.AsSpan().TrimStart('/');
if (trimmed.StartsWith(handlerPath.AsSpan(), StringComparison.OrdinalIgnoreCase))
{
return trimmed.Slice(handlerPath.Length).ToString().AsSpan();
}
}
return pathInfo.AsSpan();
}
}
}

View File

@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using IRequest = MediaBrowser.Model.Services.IRequest;
namespace Emby.Server.Implementations.SocketSharp
{
public class WebSocketSharpResponse : IResponse
{
private readonly ILogger _logger;
public WebSocketSharpResponse(ILogger logger, HttpResponse response)
{
_logger = logger;
OriginalResponse = response;
}
public HttpResponse OriginalResponse { get; }
public int StatusCode
{
get => OriginalResponse.StatusCode;
set => OriginalResponse.StatusCode = value;
}
public string StatusDescription { get; set; }
public string ContentType
{
get => OriginalResponse.ContentType;
set => OriginalResponse.ContentType = value;
}
public void AddHeader(string name, string value)
{
if (string.Equals(name, "Content-Type", StringComparison.OrdinalIgnoreCase))
{
ContentType = value;
return;
}
OriginalResponse.Headers.Add(name, value);
}
public void Redirect(string url)
{
OriginalResponse.Redirect(url);
}
public Stream OutputStream => OriginalResponse.Body;
public bool SendChunked { get; set; }
const int StreamCopyToBufferSize = 81920;
public async Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, IFileSystem fileSystem, IStreamHelper streamHelper, CancellationToken cancellationToken)
{
var allowAsync = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
//if (count <= 0)
//{
// allowAsync = true;
//}
var fileOpenOptions = FileOpenOptions.SequentialScan;
if (allowAsync)
{
fileOpenOptions |= FileOpenOptions.Asynchronous;
}
// use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
using (var fs = fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShareMode, fileOpenOptions))
{
if (offset > 0)
{
fs.Position = offset;
}
if (count > 0)
{
await streamHelper.CopyToAsync(fs, OutputStream, count, cancellationToken).ConfigureAwait(false);
}
else
{
await fs.CopyToAsync(OutputStream, StreamCopyToBufferSize, cancellationToken).ConfigureAwait(false);
}
}
}
}
}

View File

@@ -32,7 +32,7 @@ namespace Emby.Server.Implementations.Sorting
{
var audio = x as IHasAlbumArtist;
return audio != null ? audio.AlbumArtists.FirstOrDefault() : null;
return audio?.AlbumArtists.FirstOrDefault();
}
/// <summary>

View File

@@ -18,17 +18,17 @@ namespace Emby.Server.Implementations.Sorting
return string.Compare(GetValue(x), GetValue(y), StringComparison.CurrentCultureIgnoreCase);
}
private static string GetValue(BaseItem item)
{
var hasSeries = item as IHasSeries;
return hasSeries != null ? hasSeries.FindSeriesSortName() : null;
}
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name => ItemSortBy.SeriesSortName;
private static string GetValue(BaseItem item)
{
var hasSeries = item as IHasSeries;
return hasSeries?.FindSeriesSortName();
}
}
}

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Emby.Server.Implementations.Images;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Drawing;
@@ -20,7 +19,7 @@ namespace Emby.Server.Implementations.UserViews
{
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var view = (CollectionFolder)item;
var viewType = view.CollectionType;
@@ -56,7 +55,7 @@ namespace Emby.Server.Implementations.UserViews
includeItemTypes = new string[] { "Video", "Audio", "Photo", "Movie", "Series" };
}
var recursive = !new[] { CollectionType.Playlists }.Contains(view.CollectionType ?? string.Empty, StringComparer.OrdinalIgnoreCase);
var recursive = !string.Equals(CollectionType.Playlists, viewType, StringComparison.OrdinalIgnoreCase);
return view.GetItemList(new InternalItemsQuery
{
@@ -71,7 +70,7 @@ namespace Emby.Server.Implementations.UserViews
},
IncludeItemTypes = includeItemTypes
}).ToList();
});
}
protected override bool Supports(BaseItem item)
@@ -79,7 +78,7 @@ namespace Emby.Server.Implementations.UserViews
return item is CollectionFolder;
}
protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
var outputPath = Path.ChangeExtension(outputPathWithoutExtension, ".png");

View File

@@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.UserViews
_libraryManager = libraryManager;
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
var view = (UserView)item;
@@ -46,8 +46,7 @@ namespace Emby.Server.Implementations.UserViews
var items = result.Select(i =>
{
var episode = i as Episode;
if (episode != null)
if (i is Episode episode)
{
var series = episode.Series;
if (series != null)
@@ -58,8 +57,7 @@ namespace Emby.Server.Implementations.UserViews
return episode;
}
var season = i as Season;
if (season != null)
if (i is Season season)
{
var series = season.Series;
if (series != null)
@@ -70,8 +68,7 @@ namespace Emby.Server.Implementations.UserViews
return season;
}
var audio = i as Audio;
if (audio != null)
if (i is Audio audio)
{
var album = audio.AlbumEntity;
if (album != null && album.HasImage(ImageType.Primary))
@@ -122,7 +119,7 @@ namespace Emby.Server.Implementations.UserViews
return collectionStripViewTypes.Contains(view.ViewType ?? string.Empty);
}
protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
if (itemsWithImages.Count == 0)
{

View File

@@ -24,7 +24,7 @@ namespace Emby.Server.Implementations.UserViews
_libraryManager = libraryManager;
}
protected override List<BaseItem> GetItemsWithImages(BaseItem item)
protected override IReadOnlyList<BaseItem> GetItemsWithImages(BaseItem item)
{
return _libraryManager.GetItemList(new InternalItemsQuery
{
@@ -40,7 +40,7 @@ namespace Emby.Server.Implementations.UserViews
});
}
protected override string CreateImage(BaseItem item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
protected override string CreateImage(BaseItem item, IReadOnlyCollection<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex)
{
return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary);
}

View File

@@ -0,0 +1,10 @@
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
namespace Emby.Server.Implementations.WebSockets
{
public interface IWebSocketHandler
{
Task ProcessMessage(WebSocketMessage<object> message, TaskCompletionSource<bool> taskCompletionSource);
}
}

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using UtfUnknown;
namespace Emby.Server.Implementations.WebSockets
{
public class WebSocketManager
{
private readonly IWebSocketHandler[] _webSocketHandlers;
private readonly IJsonSerializer _jsonSerializer;
private readonly ILogger<WebSocketManager> _logger;
private const int BufferSize = 4096;
public WebSocketManager(IWebSocketHandler[] webSocketHandlers, IJsonSerializer jsonSerializer, ILogger<WebSocketManager> logger)
{
_webSocketHandlers = webSocketHandlers;
_jsonSerializer = jsonSerializer;
_logger = logger;
}
public async Task OnWebSocketConnected(WebSocket webSocket)
{
var taskCompletionSource = new TaskCompletionSource<bool>();
var cancellationToken = new CancellationTokenSource().Token;
WebSocketReceiveResult result;
var message = new List<byte>();
// Keep listening for incoming messages, otherwise the socket closes automatically
do
{
var buffer = WebSocket.CreateServerBuffer(BufferSize);
result = await webSocket.ReceiveAsync(buffer, cancellationToken);
message.AddRange(buffer.Array.Take(result.Count));
if (result.EndOfMessage)
{
await ProcessMessage(message.ToArray(), taskCompletionSource);
message.Clear();
}
} while (!taskCompletionSource.Task.IsCompleted &&
webSocket.State == WebSocketState.Open &&
result.MessageType != WebSocketMessageType.Close);
if (webSocket.State == WebSocketState.Open)
{
await webSocket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
result.CloseStatusDescription, cancellationToken);
}
}
private async Task ProcessMessage(byte[] messageBytes, TaskCompletionSource<bool> taskCompletionSource)
{
var charset = CharsetDetector.DetectFromBytes(messageBytes).Detected?.EncodingName;
var message = string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase)
? Encoding.UTF8.GetString(messageBytes, 0, messageBytes.Length)
: Encoding.ASCII.GetString(messageBytes, 0, messageBytes.Length);
// All messages are expected to be valid JSON objects
if (!message.StartsWith("{", StringComparison.OrdinalIgnoreCase))
{
_logger.LogDebug("Received web socket message that is not a json structure: {Message}", message);
return;
}
try
{
var info = _jsonSerializer.DeserializeFromString<WebSocketMessage<object>>(message);
_logger.LogDebug("Websocket message received: {0}", info.MessageType);
var tasks = _webSocketHandlers.Select(handler => Task.Run(() =>
{
try
{
handler.ProcessMessage(info, taskCompletionSource).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "{HandlerType} failed processing WebSocket message {MessageType}",
handler.GetType().Name, info.MessageType ?? string.Empty);
}
}));
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing web socket message");
}
}
}
}

View File

@@ -1,20 +0,0 @@
using System.Xml;
using MediaBrowser.Model.Xml;
namespace Emby.Server.Implementations.Xml
{
public class XmlReaderSettingsFactory : IXmlReaderSettingsFactory
{
public XmlReaderSettings Create(bool enableValidation)
{
var settings = new XmlReaderSettings();
if (!enableValidation)
{
settings.ValidationType = ValidationType.None;
}
return settings;
}
}
}