diff options
| -rw-r--r-- | Dockerfile | 8 | ||||
| -rw-r--r-- | Emby.Naming/Emby.Naming.csproj | 11 | ||||
| -rw-r--r-- | Emby.Server.Implementations/ApplicationHost.cs | 5 | ||||
| -rw-r--r-- | Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs | 2 | ||||
| -rw-r--r-- | Emby.Server.Implementations/HttpServer/HttpListenerHost.cs | 130 | ||||
| -rw-r--r-- | Emby.Server.Implementations/HttpServer/HttpResultFactory.cs | 39 | ||||
| -rw-r--r-- | Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs | 5 | ||||
| -rw-r--r-- | Emby.Server.Implementations/HttpServer/ResponseFilter.cs | 28 | ||||
| -rw-r--r-- | Emby.Server.Implementations/Services/HttpResult.cs | 10 | ||||
| -rw-r--r-- | Emby.Server.Implementations/Services/RequestHelper.cs | 2 | ||||
| -rw-r--r-- | Jellyfin.Server/Program.cs | 679 |
11 files changed, 456 insertions, 463 deletions
diff --git a/Dockerfile b/Dockerfile index 02332d40b..b014afcd2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -26,6 +26,12 @@ COPY --from=builder /jellyfin /jellyfin COPY --from=ffmpeg /ffmpeg-bin/* /usr/bin/ EXPOSE 8096 VOLUME /config /media + +# libfontconfig1 is required for Skia RUN apt-get update \ - && apt-get install -y libfontconfig1 --no-install-recommends # needed for Skia + && apt-get install --no-install-recommends --no-install-suggests -y \ + libfontconfig1 \ + && apt-get clean autoclean \ + && apt-get autoremove \ + && rm -rf /var/lib/{apt,dpkg,cache,log} ENTRYPOINT dotnet /jellyfin/jellyfin.dll -programdata /config diff --git a/Emby.Naming/Emby.Naming.csproj b/Emby.Naming/Emby.Naming.csproj index 360ffaabe..de40a39d2 100644 --- a/Emby.Naming/Emby.Naming.csproj +++ b/Emby.Naming/Emby.Naming.csproj @@ -5,12 +5,19 @@ <GenerateAssemblyInfo>false</GenerateAssemblyInfo> </PropertyGroup> + <PropertyGroup> + <Authors>Jellyfin Contributors</Authors> + <PackageId>Jellyfin.Naming</PackageId> + <PackageLicenseUrl>https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt</PackageLicenseUrl> + <RepositoryUrl>https://github.com/jellyfin/jellyfin</RepositoryUrl> + </PropertyGroup> + <ItemGroup> <Compile Include="..\SharedVersion.cs" Link="SharedVersion.cs" /> </ItemGroup> - + <ItemGroup> <ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" /> </ItemGroup> - + </Project> diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index e97557588..283d6b6d7 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -230,7 +230,6 @@ namespace Emby.Server.Implementations { get { - #if BETA return PackageVersionClass.Beta; #endif @@ -510,7 +509,7 @@ namespace Emby.Server.Implementations protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true) where T : class { - Container.RegisterSingleton(obj); + Container.RegisterInstance<T>(obj); if (manageLifetime) { @@ -575,7 +574,7 @@ namespace Emby.Server.Implementations } catch (Exception ex) { - Logger.LogError(ex, "Error loading assembly {file}", file); + Logger.LogError(ex, "Error loading assembly {File}", file); return null; } } diff --git a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs index 6494f0c6f..2f5eed547 100644 --- a/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs +++ b/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs @@ -389,7 +389,7 @@ namespace Emby.Server.Implementations.HttpClientManager { options.ResourcePool?.Release(); - throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true }; + throw new HttpException($"Connection to {options.Url} timed out") { IsTimedOut = true }; } if (options.LogRequest) diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 8219b85a2..6b4f2bced 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -1,26 +1,26 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Net; -using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; +using Emby.Server.Implementations.Net; using Emby.Server.Implementations.Services; +using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Net; +using MediaBrowser.Model.Events; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Services; using MediaBrowser.Model.Text; -using System.Net.Sockets; -using Emby.Server.Implementations.Net; -using MediaBrowser.Model.Events; +using Microsoft.Extensions.Logging; namespace Emby.Server.Implementations.HttpServer { @@ -54,39 +54,33 @@ namespace Emby.Server.Implementations.HttpServer private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>(); private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>(); - public HttpListenerHost(IServerApplicationHost applicationHost, + public HttpListenerHost( + IServerApplicationHost applicationHost, ILogger logger, IServerConfigurationManager config, - string defaultRedirectPath, INetworkManager networkManager, ITextEncoding textEncoding, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, Func<Type, Func<string, object>> funcParseFn) + string defaultRedirectPath, + INetworkManager networkManager, + ITextEncoding textEncoding, + IJsonSerializer jsonSerializer, + IXmlSerializer xmlSerializer, + Func<Type, Func<string, object>> funcParseFn) { - Instance = this; - _appHost = applicationHost; + _logger = logger; + _config = config; DefaultRedirectPath = defaultRedirectPath; _networkManager = networkManager; _textEncoding = textEncoding; _jsonSerializer = jsonSerializer; _xmlSerializer = xmlSerializer; - _config = config; - - _logger = logger; _funcParseFn = funcParseFn; - ResponseFilters = new Action<IRequest, IResponse, object>[] { }; + Instance = this; + ResponseFilters = Array.Empty<Action<IRequest, IResponse, object>>(); } public string GlobalResponse { get; set; } - readonly Dictionary<Type, int> _mapExceptionToStatusCode = new Dictionary<Type, int> - { - {typeof (ResourceNotFoundException), 404}, - {typeof (RemoteServiceUnavailableException), 502}, - {typeof (FileNotFoundException), 404}, - //{typeof (DirectoryNotFoundException), 404}, - {typeof (SecurityException), 401}, - {typeof (ArgumentException), 400} - }; - protected ILogger Logger => _logger; public object CreateInstance(Type type) @@ -103,9 +97,9 @@ namespace Emby.Server.Implementations.HttpServer { //Exec all RequestFilter attributes with Priority < 0 var attributes = GetRequestFilterAttributes(requestDto.GetType()); - var i = 0; - var count = attributes.Count; + int count = attributes.Count; + int i = 0; for (; i < count && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; @@ -168,10 +162,7 @@ namespace Emby.Server.Implementations.HttpServer _webSocketConnections.Add(connection); } - if (WebSocketConnected != null) - { - WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); - } + WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); } private void Connection_Closed(object sender, EventArgs e) @@ -206,27 +197,16 @@ namespace Emby.Server.Implementations.HttpServer private int GetStatusCode(Exception ex) { - if (ex is ArgumentException) + switch (ex) { - return 400; - } - - var exceptionType = ex.GetType(); - - int statusCode; - if (!_mapExceptionToStatusCode.TryGetValue(exceptionType, out statusCode)) - { - if (ex is DirectoryNotFoundException) - { - statusCode = 404; - } - else - { - statusCode = 500; - } + case ArgumentException _: return 400; + case SecurityException _: return 401; + case DirectoryNotFoundException _: + case FileNotFoundException _: + case ResourceNotFoundException _: return 404; + case RemoteServiceUnavailableException _: return 502; + default: return 500; } - - return statusCode; } private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage) @@ -312,29 +292,22 @@ namespace Emby.Server.Implementations.HttpServer } } - private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) + private static readonly string[] _skipLogExtensions = { - {".js", 0}, - {".css", 0}, - {".woff", 0}, - {".woff2", 0}, - {".ttf", 0}, - {".html", 0} + ".js", + ".css", + ".woff", + ".woff2", + ".ttf", + ".html" }; private bool EnableLogging(string url, string localPath) { var extension = GetExtension(url); - if (string.IsNullOrEmpty(extension) || !_skipLogExtensions.ContainsKey(extension)) - { - if (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1) - { - return true; - } - } - - return false; + return ((string.IsNullOrEmpty(extension) || !_skipLogExtensions.Contains(extension)) + && (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)); } private static string GetExtension(string url) @@ -557,9 +530,7 @@ namespace Emby.Server.Implementations.HttpServer return; } - if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || - string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || - localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) + if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; @@ -714,7 +685,7 @@ 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; } @@ -728,14 +699,13 @@ namespace Emby.Server.Implementations.HttpServer private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url) { - int currentPort; - Uri uri; - if (Uri.TryCreate(url, UriKind.Absolute, out uri)) + if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { - currentPort = uri.Port; - var builder = new UriBuilder(uri); - builder.Port = _config.Configuration.PublicHttpsPort; - builder.Scheme = "https"; + var builder = new UriBuilder(uri) + { + Port = _config.Configuration.PublicHttpsPort, + Scheme = "https" + }; url = builder.Uri.ToString(); RedirectToUrl(httpRes, url); @@ -835,12 +805,6 @@ namespace Emby.Server.Implementations.HttpServer public Task<object> DeserializeJson(Type type, Stream stream) { - //using (var reader = new StreamReader(stream)) - //{ - // var json = reader.ReadToEnd(); - // logger.LogInformation(json); - // return _jsonSerializer.DeserializeFromString(json, type); - //} return _jsonSerializer.DeserializeFromStreamAsync(stream, type); } diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index e6dbcf65d..bacf5556f 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -412,8 +412,10 @@ namespace Emby.Server.Implementations.HttpServer serializer.WriteObject(xw, from); xw.Flush(); ms.Seek(0, SeekOrigin.Begin); - var reader = new StreamReader(ms); - return reader.ReadToEnd(); + using (var reader = new StreamReader(ms)) + { + return reader.ReadToEnd(); + } } } } @@ -425,7 +427,7 @@ namespace Emby.Server.Implementations.HttpServer { responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString); - var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; + bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; if (!noCache) { @@ -463,8 +465,7 @@ namespace Emby.Server.Implementations.HttpServer }); } - public Task<object> GetStaticFileResult(IRequest requestContext, - StaticFileResultOptions options) + public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options) { var path = options.Path; var fileShare = options.FileShare; @@ -699,36 +700,26 @@ namespace Emby.Server.Implementations.HttpServer var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since"); - if (!string.IsNullOrEmpty(ifModifiedSinceHeader)) + if (!string.IsNullOrEmpty(ifModifiedSinceHeader) + && DateTime.TryParse(ifModifiedSinceHeader, out DateTime ifModifiedSince) + && IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) { - DateTime ifModifiedSince; - - if (DateTime.TryParse(ifModifiedSinceHeader, out ifModifiedSince)) - { - if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) - { - return true; - } - } + return true; } var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match"); - var hasCacheKey = !cacheKey.Equals(Guid.Empty); + bool hasCacheKey = !cacheKey.Equals(Guid.Empty); // Validate If-None-Match - if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader))) + if ((hasCacheKey && !string.IsNullOrEmpty(ifNoneMatchHeader))) { - Guid ifNoneMatch; - ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"'); - if (Guid.TryParse(ifNoneMatchHeader, out ifNoneMatch)) + if (Guid.TryParse(ifNoneMatchHeader, out Guid ifNoneMatch) + && cacheKey.Equals(ifNoneMatch)) { - if (hasCacheKey && cacheKey.Equals(ifNoneMatch)) - { - return true; - } + return true; } } diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index f08112f9c..ef47a7ca9 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -40,8 +40,6 @@ namespace Emby.Server.Implementations.HttpServer /// </summary> private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - public List<Cookie> Cookies { get; private set; } - /// <summary> /// Additional HTTP Headers /// </summary> @@ -72,7 +70,6 @@ namespace Emby.Server.Implementations.HttpServer Headers["Accept-Ranges"] = "bytes"; StatusCode = HttpStatusCode.PartialContent; - Cookies = new List<Cookie>(); SetRangeValues(contentLength); } @@ -220,7 +217,5 @@ namespace Emby.Server.Implementations.HttpServer get => (HttpStatusCode)Status; set => Status = (int)value; } - - public string StatusDescription { get; set; } } } diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index f38aa5ea0..afaee59f3 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -25,14 +25,11 @@ namespace Emby.Server.Implementations.HttpServer public void FilterResponse(IRequest req, IResponse res, object dto) { // Try to prevent compatibility view - //res.AddHeader("X-UA-Compatible", "IE=Edge"); 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-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); res.AddHeader("Access-Control-Allow-Origin", "*"); - var exception = dto as Exception; - - if (exception != null) + if (dto is Exception exception) { _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl); @@ -45,43 +42,26 @@ namespace Emby.Server.Implementations.HttpServer } } - var hasHeaders = dto as IHasHeaders; - - if (hasHeaders != null) + if (dto is IHasHeaders hasHeaders) { if (!hasHeaders.Headers.ContainsKey("Server")) { hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50"; - //hasHeaders.Headers["Server"] = "Mono-HTTPAPI/1.1"; } // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy - string contentLength; - - if (hasHeaders.Headers.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength)) + if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength) + && !string.IsNullOrEmpty(contentLength)) { var length = long.Parse(contentLength, UsCulture); if (length > 0) { res.SetContentLength(length); - - //var listenerResponse = res.OriginalResponse as HttpListenerResponse; - - //if (listenerResponse != null) - //{ - // // Disable chunked encoding. Technically this is only needed when using Content-Range, but - // // anytime we know the content length there's no need for it - // listenerResponse.SendChunked = false; - // return; - //} - res.SendChunked = false; } } } - - //res.KeepAlive = false; } /// <summary> diff --git a/Emby.Server.Implementations/Services/HttpResult.cs b/Emby.Server.Implementations/Services/HttpResult.cs index 7ce41a368..296da2f7a 100644 --- a/Emby.Server.Implementations/Services/HttpResult.cs +++ b/Emby.Server.Implementations/Services/HttpResult.cs @@ -15,7 +15,6 @@ namespace Emby.Server.Implementations.Services public HttpResult(object response, string contentType, HttpStatusCode statusCode) { this.Headers = new Dictionary<string, string>(); - this.Cookies = new List<Cookie>(); this.Response = response; this.ContentType = contentType; @@ -26,8 +25,6 @@ namespace Emby.Server.Implementations.Services public IDictionary<string, string> Headers { get; private set; } - public List<Cookie> Cookies { get; private set; } - public int Status { get; set; } public HttpStatusCode StatusCode @@ -40,15 +37,16 @@ namespace Emby.Server.Implementations.Services public async Task WriteToAsync(Stream responseStream, CancellationToken cancellationToken) { - var response = RequestContext != null ? RequestContext.Response : null; + var response = RequestContext == null ? null : RequestContext.Response; - var bytesResponse = this.Response as byte[]; - if (bytesResponse != null) + if (this.Response is byte[] bytesResponse) { var contentLength = bytesResponse.Length; if (response != null) + { response.SetContentLength(contentLength); + } if (contentLength > 0) { diff --git a/Emby.Server.Implementations/Services/RequestHelper.cs b/Emby.Server.Implementations/Services/RequestHelper.cs index 711ba8bbc..7d2fbc3e0 100644 --- a/Emby.Server.Implementations/Services/RequestHelper.cs +++ b/Emby.Server.Implementations/Services/RequestHelper.cs @@ -49,4 +49,4 @@ namespace Emby.Server.Implementations.Services } } -}
\ No newline at end of file +} diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index d74315755..46a80b492 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -1,313 +1,366 @@ -using System;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Security;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Emby.Drawing;
-using Emby.Drawing.Skia;
-using Emby.Server.Implementations;
-using Emby.Server.Implementations.EnvironmentInfo;
-using Emby.Server.Implementations.IO;
-using Emby.Server.Implementations.Networking;
-using MediaBrowser.Common.Configuration;
-using MediaBrowser.Common.Net;
-using MediaBrowser.Controller.Drawing;
-using MediaBrowser.Model.IO;
-using MediaBrowser.Model.Globalization;
-using MediaBrowser.Model.System;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
-using Serilog;
-using Serilog.AspNetCore;
-using ILogger = Microsoft.Extensions.Logging.ILogger;
-
-namespace Jellyfin.Server
-{
- public static class Program
- {
- private static readonly TaskCompletionSource<bool> ApplicationTaskCompletionSource = new TaskCompletionSource<bool>();
- private static ILoggerFactory _loggerFactory;
- private static ILogger _logger;
- private static bool _restartOnShutdown;
-
- public static async Task<int> Main(string[] args)
- {
- StartupOptions options = new StartupOptions(args);
- Version version = Assembly.GetEntryAssembly().GetName().Version;
-
- if (options.ContainsOption("-v") || options.ContainsOption("--version"))
- {
- Console.WriteLine(version.ToString());
- return 0;
- }
-
- ServerApplicationPaths appPaths = createApplicationPaths(options);
- // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager
- Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath);
- await createLogger(appPaths);
- _loggerFactory = new SerilogLoggerFactory();
- _logger = _loggerFactory.CreateLogger("Main");
-
- AppDomain.CurrentDomain.UnhandledException += (sender, e)
- => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception");
-
- _logger.LogInformation("Jellyfin version: {Version}", version);
-
- EnvironmentInfo environmentInfo = new EnvironmentInfo(getOperatingSystem());
- ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo);
-
- SQLitePCL.Batteries_V2.Init();
-
- // Allow all https requests
- ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
-
- var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true);
-
- using (var appHost = new CoreAppHost(
- appPaths,
- _loggerFactory,
- options,
- fileSystem,
- environmentInfo,
- new NullImageEncoder(),
- new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")),
- new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo)))
- {
- appHost.Init();
-
- appHost.ImageProcessor.ImageEncoder = getImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager);
-
- _logger.LogInformation("Running startup tasks");
-
- await appHost.RunStartupTasks();
-
- // TODO: read input for a stop command
- // Block main thread until shutdown
- await ApplicationTaskCompletionSource.Task;
-
- _logger.LogInformation("Disposing app host");
- }
-
- if (_restartOnShutdown)
- {
- StartNewInstance(options);
- }
-
- return 0;
- }
-
- private static ServerApplicationPaths createApplicationPaths(StartupOptions options)
- {
- string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH");
- if (string.IsNullOrEmpty(programDataPath))
- {
- if (options.ContainsOption("-programdata"))
- {
- programDataPath = options.GetOption("-programdata");
- }
- else
- {
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
- }
- else
- {
- // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored.
- programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
- // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used.
- if (string.IsNullOrEmpty(programDataPath))
- {
- programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share");
- }
- }
- programDataPath = Path.Combine(programDataPath, "jellyfin");
- // Ensure the dir exists
- Directory.CreateDirectory(programDataPath);
- }
- }
-
- string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR");
- if (string.IsNullOrEmpty(configDir))
- {
- if (options.ContainsOption("-configdir"))
- {
- configDir = options.GetOption("-configdir");
- }
- else
- {
- // Let BaseApplicationPaths set up the default value
- configDir = null;
- }
- }
-
- string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR");
- if (string.IsNullOrEmpty(logDir))
- {
- if (options.ContainsOption("-logdir"))
- {
- logDir = options.GetOption("-logdir");
- }
- else
- {
- // Let BaseApplicationPaths set up the default value
- logDir = null;
- }
- }
-
- string appPath = AppContext.BaseDirectory;
-
- return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir);
- }
-
- private static async Task createLogger(IApplicationPaths appPaths)
- {
- try
- {
- string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json");
-
- if (!File.Exists(configPath))
- {
- // For some reason the csproj name is used instead of the assembly name
- using (Stream rscstr = typeof(Program).Assembly
- .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json"))
- using (Stream fstr = File.Open(configPath, FileMode.CreateNew))
- {
- await rscstr.CopyToAsync(fstr);
- }
- }
- var configuration = new ConfigurationBuilder()
- .SetBasePath(appPaths.ConfigurationDirectoryPath)
- .AddJsonFile("logging.json")
- .AddEnvironmentVariables("JELLYFIN_")
- .Build();
-
- // Serilog.Log is used by SerilogLoggerFactory when no logger is specified
- Serilog.Log.Logger = new LoggerConfiguration()
- .ReadFrom.Configuration(configuration)
- .Enrich.FromLogContext()
- .CreateLogger();
- }
- catch (Exception ex)
- {
- Serilog.Log.Logger = new LoggerConfiguration()
- .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}")
- .WriteTo.Async(x => x.File(
- Path.Combine(appPaths.LogDirectoryPath, "log_.log"),
- rollingInterval: RollingInterval.Day,
- outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}"))
- .Enrich.FromLogContext()
- .CreateLogger();
-
- Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration");
- }
- }
-
- public static IImageEncoder getImageEncoder(
- ILogger logger,
- IFileSystem fileSystem,
- StartupOptions startupOptions,
- Func<IHttpClient> httpClient,
- IApplicationPaths appPaths,
- IEnvironmentInfo environment,
- ILocalizationManager localizationManager)
- {
- try
- {
- return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager);
- }
- catch (Exception ex)
- {
- logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}");
- }
-
- return new NullImageEncoder();
- }
-
- private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() {
- switch (Environment.OSVersion.Platform)
- {
- case PlatformID.MacOSX:
- return MediaBrowser.Model.System.OperatingSystem.OSX;
- case PlatformID.Win32NT:
- return MediaBrowser.Model.System.OperatingSystem.Windows;
- case PlatformID.Unix:
- default:
- {
- string osDescription = RuntimeInformation.OSDescription;
- if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase))
- {
- return MediaBrowser.Model.System.OperatingSystem.Linux;
- }
- else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase))
- {
- return MediaBrowser.Model.System.OperatingSystem.OSX;
- }
- else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase))
- {
- return MediaBrowser.Model.System.OperatingSystem.BSD;
- }
- throw new Exception($"Can't resolve OS with description: '{osDescription}'");
- }
- }
- }
-
- public static void Shutdown()
- {
- ApplicationTaskCompletionSource.SetResult(true);
- }
-
- public static void Restart()
- {
- _restartOnShutdown = true;
-
- Shutdown();
- }
-
- private static void StartNewInstance(StartupOptions startupOptions)
- {
- _logger.LogInformation("Starting new instance");
-
- string module = startupOptions.GetOption("-restartpath");
-
- if (string.IsNullOrWhiteSpace(module))
- {
- module = Environment.GetCommandLineArgs().First();
- }
-
- string commandLineArgsString;
-
- if (startupOptions.ContainsOption("-restartargs"))
- {
- commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty;
- }
- else
- {
- commandLineArgsString = string .Join(" ",
- Environment.GetCommandLineArgs()
- .Skip(1)
- .Select(NormalizeCommandLineArgument)
- );
- }
-
- _logger.LogInformation("Executable: {0}", module);
- _logger.LogInformation("Arguments: {0}", commandLineArgsString);
-
- Process.Start(module, commandLineArgsString);
- }
-
- private static string NormalizeCommandLineArgument(string arg)
- {
- if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase))
- {
- return arg;
- }
-
- return "\"" + arg + "\"";
- }
- }
-}
+using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Security; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Emby.Drawing; +using Emby.Drawing.Skia; +using Emby.Server.Implementations; +using Emby.Server.Implementations.EnvironmentInfo; +using Emby.Server.Implementations.IO; +using Emby.Server.Implementations.Networking; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Drawing; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.System; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.AspNetCore; +using ILogger = Microsoft.Extensions.Logging.ILogger; + +namespace Jellyfin.Server +{ + public static class Program + { + private static readonly CancellationTokenSource _tokenSource = new CancellationTokenSource(); + private static readonly ILoggerFactory _loggerFactory = new SerilogLoggerFactory(); + private static ILogger _logger; + private static bool _restartOnShutdown; + + public static async Task Main(string[] args) + { + StartupOptions options = new StartupOptions(args); + Version version = Assembly.GetEntryAssembly().GetName().Version; + + if (options.ContainsOption("-v") || options.ContainsOption("--version")) + { + Console.WriteLine(version.ToString()); + } + + ServerApplicationPaths appPaths = CreateApplicationPaths(options); + + // $JELLYFIN_LOG_DIR needs to be set for the logger configuration manager + Environment.SetEnvironmentVariable("JELLYFIN_LOG_DIR", appPaths.LogDirectoryPath); + await createLogger(appPaths); + _logger = _loggerFactory.CreateLogger("Main"); + + AppDomain.CurrentDomain.UnhandledException += (sender, e) + => _logger.LogCritical((Exception)e.ExceptionObject, "Unhandled Exception"); + + // Intercept Ctrl+C and Ctrl+Break + Console.CancelKeyPress += (sender, e) => + { + if (_tokenSource.IsCancellationRequested) + { + return; // Already shutting down + } + e.Cancel = true; + _logger.LogInformation("Ctrl+C, shutting down"); + Environment.ExitCode = 128 + 2; + Shutdown(); + }; + + // Register a SIGTERM handler + AppDomain.CurrentDomain.ProcessExit += (sender, e) => + { + if (_tokenSource.IsCancellationRequested) + { + return; // Already shutting down + } + _logger.LogInformation("Received a SIGTERM signal, shutting down"); + Environment.ExitCode = 128 + 15; + Shutdown(); + }; + + _logger.LogInformation("Jellyfin version: {Version}", version); + + EnvironmentInfo environmentInfo = new EnvironmentInfo(getOperatingSystem()); + ApplicationHost.LogEnvironmentInfo(_logger, appPaths, environmentInfo); + + SQLitePCL.Batteries_V2.Init(); + + // Allow all https requests + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; }); + + var fileSystem = new ManagedFileSystem(_loggerFactory.CreateLogger("FileSystem"), environmentInfo, null, appPaths.TempDirectory, true); + + using (var appHost = new CoreAppHost( + appPaths, + _loggerFactory, + options, + fileSystem, + environmentInfo, + new NullImageEncoder(), + new SystemEvents(_loggerFactory.CreateLogger("SystemEvents")), + new NetworkManager(_loggerFactory.CreateLogger("NetworkManager"), environmentInfo))) + { + appHost.Init(); + + appHost.ImageProcessor.ImageEncoder = getImageEncoder(_logger, fileSystem, options, () => appHost.HttpClient, appPaths, environmentInfo, appHost.LocalizationManager); + + _logger.LogInformation("Running startup tasks"); + + await appHost.RunStartupTasks(); + + // TODO: read input for a stop command + + try + { + // Block main thread until shutdown + await Task.Delay(-1, _tokenSource.Token); + } + catch (TaskCanceledException) + { + // Don't throw on cancellation + } + + _logger.LogInformation("Disposing app host"); + } + + if (_restartOnShutdown) + { + StartNewInstance(options); + } + } + + private static ServerApplicationPaths CreateApplicationPaths(StartupOptions options) + { + string programDataPath = Environment.GetEnvironmentVariable("JELLYFIN_DATA_PATH"); + if (string.IsNullOrEmpty(programDataPath)) + { + if (options.ContainsOption("-programdata")) + { + programDataPath = options.GetOption("-programdata"); + } + else + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + } + else + { + // $XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored. + programDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); + // If $XDG_DATA_HOME is either not set or empty, $HOME/.local/share should be used. + if (string.IsNullOrEmpty(programDataPath)) + { + programDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share"); + } + } + + programDataPath = Path.Combine(programDataPath, "jellyfin"); + } + } + + if (string.IsNullOrEmpty(programDataPath)) + { + Console.WriteLine("Cannot continue without path to program data folder (try -programdata)"); + Environment.Exit(1); + } + else + { + Directory.CreateDirectory(programDataPath); + } + + string configDir = Environment.GetEnvironmentVariable("JELLYFIN_CONFIG_DIR"); + if (string.IsNullOrEmpty(configDir)) + { + if (options.ContainsOption("-configdir")) + { + configDir = options.GetOption("-configdir"); + } + else + { + // Let BaseApplicationPaths set up the default value + configDir = null; + } + } + + if (configDir != null) + { + Directory.CreateDirectory(configDir); + } + + string logDir = Environment.GetEnvironmentVariable("JELLYFIN_LOG_DIR"); + if (string.IsNullOrEmpty(logDir)) + { + if (options.ContainsOption("-logdir")) + { + logDir = options.GetOption("-logdir"); + } + else + { + // Let BaseApplicationPaths set up the default value + logDir = null; + } + } + + if (logDir != null) + { + Directory.CreateDirectory(logDir); + } + + string appPath = AppContext.BaseDirectory; + + return new ServerApplicationPaths(programDataPath, appPath, appPath, logDir, configDir); + } + + private static async Task createLogger(IApplicationPaths appPaths) + { + try + { + string configPath = Path.Combine(appPaths.ConfigurationDirectoryPath, "logging.json"); + + if (!File.Exists(configPath)) + { + // For some reason the csproj name is used instead of the assembly name + using (Stream rscstr = typeof(Program).Assembly + .GetManifestResourceStream("Jellyfin.Server.Resources.Configuration.logging.json")) + using (Stream fstr = File.Open(configPath, FileMode.CreateNew)) + { + await rscstr.CopyToAsync(fstr); + } + } + var configuration = new ConfigurationBuilder() + .SetBasePath(appPaths.ConfigurationDirectoryPath) + .AddJsonFile("logging.json") + .AddEnvironmentVariables("JELLYFIN_") + .Build(); + + // Serilog.Log is used by SerilogLoggerFactory when no logger is specified + Serilog.Log.Logger = new LoggerConfiguration() + .ReadFrom.Configuration(configuration) + .Enrich.FromLogContext() + .CreateLogger(); + } + catch (Exception ex) + { + Serilog.Log.Logger = new LoggerConfiguration() + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Async(x => x.File( + Path.Combine(appPaths.LogDirectoryPath, "log_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] {Message}{NewLine}{Exception}")) + .Enrich.FromLogContext() + .CreateLogger(); + + Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration"); + } + } + + public static IImageEncoder getImageEncoder( + ILogger logger, + IFileSystem fileSystem, + StartupOptions startupOptions, + Func<IHttpClient> httpClient, + IApplicationPaths appPaths, + IEnvironmentInfo environment, + ILocalizationManager localizationManager) + { + try + { + return new SkiaEncoder(logger, appPaths, httpClient, fileSystem, localizationManager); + } + catch (Exception ex) + { + logger.LogInformation(ex, "Skia not available. Will fallback to NullIMageEncoder. {0}"); + } + + return new NullImageEncoder(); + } + + private static MediaBrowser.Model.System.OperatingSystem getOperatingSystem() { + switch (Environment.OSVersion.Platform) + { + case PlatformID.MacOSX: + return MediaBrowser.Model.System.OperatingSystem.OSX; + case PlatformID.Win32NT: + return MediaBrowser.Model.System.OperatingSystem.Windows; + case PlatformID.Unix: + default: + { + string osDescription = RuntimeInformation.OSDescription; + if (osDescription.Contains("linux", StringComparison.OrdinalIgnoreCase)) + { + return MediaBrowser.Model.System.OperatingSystem.Linux; + } + else if (osDescription.Contains("darwin", StringComparison.OrdinalIgnoreCase)) + { + return MediaBrowser.Model.System.OperatingSystem.OSX; + } + else if (osDescription.Contains("bsd", StringComparison.OrdinalIgnoreCase)) + { + return MediaBrowser.Model.System.OperatingSystem.BSD; + } + throw new Exception($"Can't resolve OS with description: '{osDescription}'"); + } + } + } + + public static void Shutdown() + { + if (!_tokenSource.IsCancellationRequested) + { + _tokenSource.Cancel(); + } + } + + public static void Restart() + { + _restartOnShutdown = true; + + Shutdown(); + } + + private static void StartNewInstance(StartupOptions startupOptions) + { + _logger.LogInformation("Starting new instance"); + + string module = startupOptions.GetOption("-restartpath"); + + if (string.IsNullOrWhiteSpace(module)) + { + module = Environment.GetCommandLineArgs().First(); + } + + string commandLineArgsString; + + if (startupOptions.ContainsOption("-restartargs")) + { + commandLineArgsString = startupOptions.GetOption("-restartargs") ?? string.Empty; + } + else + { + commandLineArgsString = string .Join(" ", + Environment.GetCommandLineArgs() + .Skip(1) + .Select(NormalizeCommandLineArgument) + ); + } + + _logger.LogInformation("Executable: {0}", module); + _logger.LogInformation("Arguments: {0}", commandLineArgsString); + + Process.Start(module, commandLineArgsString); + } + + private static string NormalizeCommandLineArgument(string arg) + { + if (!arg.Contains(" ", StringComparison.OrdinalIgnoreCase)) + { + return arg; + } + + return "\"" + arg + "\""; + } + } +} |
