< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.ApplicationHost
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/ApplicationHost.cs
Line coverage
74%
Covered lines: 285
Uncovered lines: 96
Coverable lines: 381
Total lines: 1042
Line coverage: 74.8%
Branch coverage
45%
Covered branches: 58
Total branches: 128
Branch coverage: 45.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 3/5/2026 - 12:13:57 AM Line coverage: 72.1% (225/312) Branch coverage: 39.4% (41/104) Total lines: 10144/19/2026 - 12:14:27 AM Line coverage: 73.5% (267/363) Branch coverage: 49.2% (62/126) Total lines: 10145/4/2026 - 12:15:16 AM Line coverage: 74% (274/370) Branch coverage: 49.2% (62/126) Total lines: 10215/5/2026 - 12:15:44 AM Line coverage: 74.1% (275/371) Branch coverage: 49.2% (62/126) Total lines: 10225/12/2026 - 12:15:57 AM Line coverage: 74.1% (275/371) Branch coverage: 49.2% (63/128) Total lines: 10225/16/2026 - 12:15:55 AM Line coverage: 74.6% (282/378) Branch coverage: 49.2% (63/128) Total lines: 10385/20/2026 - 12:15:44 AM Line coverage: 74.6% (282/378) Branch coverage: 45.3% (58/128) Total lines: 10386/8/2026 - 12:16:15 AM Line coverage: 74.8% (285/381) Branch coverage: 45.3% (58/128) Total lines: 1042 3/5/2026 - 12:13:57 AM Line coverage: 72.1% (225/312) Branch coverage: 39.4% (41/104) Total lines: 10144/19/2026 - 12:14:27 AM Line coverage: 73.5% (267/363) Branch coverage: 49.2% (62/126) Total lines: 10145/4/2026 - 12:15:16 AM Line coverage: 74% (274/370) Branch coverage: 49.2% (62/126) Total lines: 10215/5/2026 - 12:15:44 AM Line coverage: 74.1% (275/371) Branch coverage: 49.2% (62/126) Total lines: 10225/12/2026 - 12:15:57 AM Line coverage: 74.1% (275/371) Branch coverage: 49.2% (63/128) Total lines: 10225/16/2026 - 12:15:55 AM Line coverage: 74.6% (282/378) Branch coverage: 49.2% (63/128) Total lines: 10385/20/2026 - 12:15:44 AM Line coverage: 74.6% (282/378) Branch coverage: 45.3% (58/128) Total lines: 10386/8/2026 - 12:16:15 AM Line coverage: 74.8% (285/381) Branch coverage: 45.3% (58/128) Total lines: 1042

Coverage delta

Coverage delta 10 -10

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_PublishedServerUrl()100%210%
get_ApplicationUserAgentAddress()100%11100%
get_SystemId()100%11100%
get_Name()100%11100%
get_ListenWithHttps()0%620%
get_FriendlyName()0%620%
ExpandVirtualPath(...)50%2280%
ReverseVirtualPath(...)100%11100%
CreateInstanceSafe(...)62.5%15852.63%
Resolve()100%11100%
GetExportTypes()100%44100%
GetExports(...)83.33%6688.88%
GetExports(...)100%66100%
RunStartupTasksAsync()50%2290.9%
Init(...)50%4481.25%
RegisterServices(...)100%11100%
InitializeServices()100%11100%
GetCertificate(...)12.5%48814.28%
SetStaticProperties()100%11100%
FindParts()50%22100%
DiscoverTypes()100%11100%
GetTypes()100%341246.66%
OnConfigurationUpdated(...)42.85%341453.33%
ValidateSslCertificate(...)33.33%15636.36%
NotifyPendingRestart()0%620%
GetComposablePartAssemblies()75%4493.75%
GetSmartApiUrl(...)0%620%
GetSmartApiUrl(...)0%210140%
GetSmartApiUrl(...)0%620%
GetApiUrlForLocalAccess(...)0%2040%
GetLocalApiUrl(...)0%110100%
GetApiPluginAssemblies()100%22100%
Dispose()100%11100%
Dispose(...)70%111077.77%

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/ApplicationHost.cs

#LineLine coverage
 1#nullable disable
 2
 3#pragma warning disable CS1591
 4
 5using System;
 6using System.Collections.Concurrent;
 7using System.Collections.Generic;
 8using System.Diagnostics;
 9using System.Globalization;
 10using System.IO;
 11using System.Linq;
 12using System.Net;
 13using System.Reflection;
 14using System.Security.Cryptography.X509Certificates;
 15using System.Threading.Tasks;
 16using Emby.Naming.Common;
 17using Emby.Naming.Video;
 18using Emby.Photos;
 19using Emby.Server.Implementations.Chapters;
 20using Emby.Server.Implementations.Collections;
 21using Emby.Server.Implementations.Configuration;
 22using Emby.Server.Implementations.Cryptography;
 23using Emby.Server.Implementations.Data;
 24using Emby.Server.Implementations.Devices;
 25using Emby.Server.Implementations.Dto;
 26using Emby.Server.Implementations.HttpServer.Security;
 27using Emby.Server.Implementations.IO;
 28using Emby.Server.Implementations.Library;
 29using Emby.Server.Implementations.Library.Search;
 30using Emby.Server.Implementations.Library.SimilarItems;
 31using Emby.Server.Implementations.Localization;
 32using Emby.Server.Implementations.Playlists;
 33using Emby.Server.Implementations.Plugins;
 34using Emby.Server.Implementations.QuickConnect;
 35using Emby.Server.Implementations.ScheduledTasks;
 36using Emby.Server.Implementations.Serialization;
 37using Emby.Server.Implementations.Session;
 38using Emby.Server.Implementations.SyncPlay;
 39using Emby.Server.Implementations.TV;
 40using Emby.Server.Implementations.Updates;
 41using Jellyfin.Api.Helpers;
 42using Jellyfin.Drawing;
 43using Jellyfin.MediaEncoding.Hls.Playlist;
 44using Jellyfin.Networking.Manager;
 45using Jellyfin.Networking.Udp;
 46using Jellyfin.Server.Implementations.FullSystemBackup;
 47using Jellyfin.Server.Implementations.Item;
 48using Jellyfin.Server.Implementations.MediaSegments;
 49using Jellyfin.Server.Implementations.SystemBackupService;
 50using MediaBrowser.Common;
 51using MediaBrowser.Common.Configuration;
 52using MediaBrowser.Common.Events;
 53using MediaBrowser.Common.Net;
 54using MediaBrowser.Common.Plugins;
 55using MediaBrowser.Common.Updates;
 56using MediaBrowser.Controller;
 57using MediaBrowser.Controller.Channels;
 58using MediaBrowser.Controller.Chapters;
 59using MediaBrowser.Controller.ClientEvent;
 60using MediaBrowser.Controller.Collections;
 61using MediaBrowser.Controller.Configuration;
 62using MediaBrowser.Controller.Drawing;
 63using MediaBrowser.Controller.Dto;
 64using MediaBrowser.Controller.Entities;
 65using MediaBrowser.Controller.Entities.TV;
 66using MediaBrowser.Controller.IO;
 67using MediaBrowser.Controller.Library;
 68using MediaBrowser.Controller.LibraryTaskScheduler;
 69using MediaBrowser.Controller.LiveTv;
 70using MediaBrowser.Controller.Lyrics;
 71using MediaBrowser.Controller.MediaEncoding;
 72using MediaBrowser.Controller.MediaSegments;
 73using MediaBrowser.Controller.Net;
 74using MediaBrowser.Controller.Persistence;
 75using MediaBrowser.Controller.Playlists;
 76using MediaBrowser.Controller.Providers;
 77using MediaBrowser.Controller.QuickConnect;
 78using MediaBrowser.Controller.Resolvers;
 79using MediaBrowser.Controller.Session;
 80using MediaBrowser.Controller.Sorting;
 81using MediaBrowser.Controller.Subtitles;
 82using MediaBrowser.Controller.SyncPlay;
 83using MediaBrowser.Controller.TV;
 84using MediaBrowser.LocalMetadata.Savers;
 85using MediaBrowser.MediaEncoding.BdInfo;
 86using MediaBrowser.MediaEncoding.Subtitles;
 87using MediaBrowser.MediaEncoding.Transcoding;
 88using MediaBrowser.Model.Cryptography;
 89using MediaBrowser.Model.Globalization;
 90using MediaBrowser.Model.IO;
 91using MediaBrowser.Model.MediaInfo;
 92using MediaBrowser.Model.Net;
 93using MediaBrowser.Model.Serialization;
 94using MediaBrowser.Model.System;
 95using MediaBrowser.Model.Tasks;
 96using MediaBrowser.Providers.Lyric;
 97using MediaBrowser.Providers.Manager;
 98using MediaBrowser.Providers.Plugins.ListenBrainz;
 99using MediaBrowser.Providers.Plugins.ListenBrainz.Api;
 100using MediaBrowser.Providers.Plugins.Tmdb;
 101using MediaBrowser.Providers.Plugins.Tmdb.Movies;
 102using MediaBrowser.Providers.Plugins.Tmdb.TV;
 103using MediaBrowser.Providers.Subtitles;
 104using MediaBrowser.XbmcMetadata.Providers;
 105using Microsoft.AspNetCore.Http;
 106using Microsoft.AspNetCore.Mvc;
 107using Microsoft.Extensions.Configuration;
 108using Microsoft.Extensions.DependencyInjection;
 109using Microsoft.Extensions.Logging;
 110using Prometheus.DotNetRuntime;
 111using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 112using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
 113using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
 114
 115namespace Emby.Server.Implementations
 116{
 117    /// <summary>
 118    /// Class CompositionRoot.
 119    /// </summary>
 120    public abstract class ApplicationHost : IServerApplicationHost, IDisposable
 121    {
 122        /// <summary>
 123        /// The disposable parts.
 124        /// </summary>
 21125        private readonly ConcurrentBag<IDisposable> _disposableParts = new();
 126        private readonly DeviceId _deviceId;
 127
 128        private readonly IConfiguration _startupConfig;
 129        private readonly IXmlSerializer _xmlSerializer;
 130        private readonly IStartupOptions _startupOptions;
 131        private readonly PluginManager _pluginManager;
 132
 133        private List<Type> _creatingInstances;
 134
 135        /// <summary>
 136        /// Gets or sets all concrete types.
 137        /// </summary>
 138        /// <value>All concrete types.</value>
 139        private Type[] _allConcreteTypes;
 140
 141        private bool _disposed;
 142
 143        /// <summary>
 144        /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
 145        /// </summary>
 146        /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
 147        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
 148        /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
 149        /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
 150        protected ApplicationHost(
 151            IServerApplicationPaths applicationPaths,
 152            ILoggerFactory loggerFactory,
 153            IStartupOptions options,
 154            IConfiguration startupConfig)
 155        {
 156            ApplicationPaths = applicationPaths;
 157            LoggerFactory = loggerFactory;
 21158            _startupOptions = options;
 21159            _startupConfig = startupConfig;
 160
 21161            Logger = LoggerFactory.CreateLogger<ApplicationHost>();
 21162            _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
 163
 21164            ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
 21165            ApplicationVersionString = ApplicationVersion.ToString(3);
 21166            ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
 167
 21168            _xmlSerializer = new MyXmlSerializer();
 21169            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
 21170            _pluginManager = new PluginManager(
 21171                LoggerFactory.CreateLogger<PluginManager>(),
 21172                this,
 21173                ConfigurationManager.Configuration,
 21174                ApplicationPaths.PluginsPath,
 21175                ApplicationVersion);
 21176        }
 177
 178        /// <summary>
 179        /// Occurs when [has pending restart changed].
 180        /// </summary>
 181        public event EventHandler HasPendingRestartChanged;
 182
 183        /// <summary>
 184        /// Gets the value of the PublishedServerUrl setting.
 185        /// </summary>
 0186        private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
 187
 188        public bool CoreStartupHasCompleted { get; private set; }
 189
 190        /// <summary>
 191        /// Gets the <see cref="INetworkManager"/> singleton instance.
 192        /// </summary>
 193        public INetworkManager NetManager { get; private set; }
 194
 195        /// <inheritdoc />
 196        public bool HasPendingRestart { get; private set; }
 197
 198        /// <inheritdoc />
 199        public bool ShouldRestart { get; set; }
 200
 201        /// <summary>
 202        /// Gets the logger.
 203        /// </summary>
 204        protected ILogger<ApplicationHost> Logger { get; }
 205
 206        /// <summary>
 207        /// Gets the logger factory.
 208        /// </summary>
 209        protected ILoggerFactory LoggerFactory { get; }
 210
 211        /// <summary>
 212        /// Gets the application paths.
 213        /// </summary>
 214        /// <value>The application paths.</value>
 215        protected IServerApplicationPaths ApplicationPaths { get; }
 216
 217        /// <summary>
 218        /// Gets the configuration manager.
 219        /// </summary>
 220        /// <value>The configuration manager.</value>
 221        public ServerConfigurationManager ConfigurationManager { get; }
 222
 223        /// <summary>
 224        /// Gets or sets the service provider.
 225        /// </summary>
 226        public IServiceProvider ServiceProvider { get; set; }
 227
 228        /// <summary>
 229        /// Gets the http port for the webhost.
 230        /// </summary>
 231        public int HttpPort { get; private set; }
 232
 233        /// <summary>
 234        /// Gets the https port for the webhost.
 235        /// </summary>
 236        public int HttpsPort { get; private set; }
 237
 238        /// <inheritdoc />
 239        public Version ApplicationVersion { get; }
 240
 241        /// <inheritdoc />
 242        public string ApplicationVersionString { get; }
 243
 244        /// <summary>
 245        /// Gets the current application user agent.
 246        /// </summary>
 247        /// <value>The application user agent.</value>
 248        public string ApplicationUserAgent { get; }
 249
 250        /// <summary>
 251        /// Gets the email address for use within a comment section of a user agent field.
 252        /// Presently used to provide contact information to MusicBrainz service.
 253        /// </summary>
 21254        public string ApplicationUserAgentAddress => "team@jellyfin.org";
 255
 256        /// <summary>
 257        /// Gets the current application name.
 258        /// </summary>
 259        /// <value>The application name.</value>
 21260        public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Locat
 261
 95262        public string SystemId => _deviceId.Value;
 263
 264        /// <inheritdoc/>
 63265        public string Name => ApplicationProductName;
 266
 267        private string CertificatePath { get; set; }
 268
 269        public X509Certificate2 Certificate { get; private set; }
 270
 271        /// <inheritdoc/>
 0272        public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableH
 273
 274        public string FriendlyName =>
 0275            string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
 0276                ? Environment.MachineName
 0277                : ConfigurationManager.Configuration.ServerName;
 278
 279        public string RestoreBackupPath { get; set; }
 280
 281        public string ExpandVirtualPath(string path)
 282        {
 72283            if (path is null)
 284            {
 0285                return null;
 286            }
 287
 72288            var appPaths = ApplicationPaths;
 289
 72290            return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
 72291                .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIg
 292        }
 293
 294        public string ReverseVirtualPath(string path)
 295        {
 111296            var appPaths = ApplicationPaths;
 297
 111298            return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
 111299                .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIg
 300        }
 301
 302        /// <summary>
 303        /// Creates the instance safe.
 304        /// </summary>
 305        /// <param name="type">The type.</param>
 306        /// <returns>System.Object.</returns>
 307        protected object CreateInstanceSafe(Type type)
 308        {
 4599309            _creatingInstances ??= new List<Type>();
 310
 4599311            if (_creatingInstances.Contains(type))
 312            {
 0313                Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
 0314                foreach (var entry in _creatingInstances)
 315                {
 0316                    Logger.LogError("Called from: {TypeName}", entry.FullName);
 317                }
 318
 0319                _pluginManager.FailPlugin(type.Assembly);
 320
 0321                throw new TypeLoadException("DI Loop detected");
 322            }
 323
 324            try
 325            {
 4599326                _creatingInstances.Add(type);
 4599327                Logger.LogDebug("Creating instance of {Type}", type);
 4599328                return ServiceProvider is null
 4599329                    ? Activator.CreateInstance(type)
 4599330                    : ActivatorUtilities.CreateInstance(ServiceProvider, type);
 331            }
 0332            catch (Exception ex)
 333            {
 0334                Logger.LogError(ex, "Error creating {Type}", type);
 335                // If this is a plugin fail it.
 0336                _pluginManager.FailPlugin(type.Assembly);
 0337                return null;
 338            }
 339            finally
 340            {
 4599341                _creatingInstances.Remove(type);
 4599342            }
 4599343        }
 344
 345        /// <summary>
 346        /// Resolves this instance.
 347        /// </summary>
 348        /// <typeparam name="T">The type.</typeparam>
 349        /// <returns>``0.</returns>
 546350        public T Resolve<T>() => ServiceProvider.GetService<T>();
 351
 352        /// <inheritdoc/>
 353        public IEnumerable<Type> GetExportTypes<T>()
 354        {
 420355            var currentType = typeof(T);
 420356            var numberOfConcreteTypes = _allConcreteTypes.Length;
 882000357            for (var i = 0; i < numberOfConcreteTypes; i++)
 358            {
 440580359                var type = _allConcreteTypes[i];
 440580360                if (currentType.IsAssignableFrom(type))
 361                {
 4830362                    yield return type;
 363                }
 364            }
 420365        }
 366
 367        /// <inheritdoc />
 368        public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
 369        {
 370            // Convert to list so this isn't executed for each iteration
 336371            var parts = GetExportTypes<T>()
 336372                .Select(CreateInstanceSafe)
 336373                .Where(i => i is not null)
 336374                .Cast<T>()
 336375                .ToList();
 376
 336377            if (manageLifetime)
 378            {
 630379                foreach (var part in parts.OfType<IDisposable>())
 380                {
 0381                    _disposableParts.Add(part);
 382                }
 383            }
 384
 336385            return parts;
 386        }
 387
 388        /// <inheritdoc />
 389        public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
 390        {
 391            // Convert to list so this isn't executed for each iteration
 21392            var parts = GetExportTypes<T>()
 21393                .Select(i => defaultFunc(i))
 21394                .Where(i => i is not null)
 21395                .Cast<T>()
 21396                .ToList();
 397
 21398            if (manageLifetime)
 399            {
 84400                foreach (var part in parts.OfType<IDisposable>())
 401                {
 21402                    _disposableParts.Add(part);
 403                }
 404            }
 405
 21406            return parts;
 407        }
 408
 409        /// <summary>
 410        /// Runs the startup tasks.
 411        /// </summary>
 412        /// <returns><see cref="Task" />.</returns>
 413        public Task RunStartupTasksAsync()
 414        {
 21415            Logger.LogInformation("Running startup tasks");
 416
 21417            Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
 418
 21419            ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
 21420            ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
 421
 21422            var ffmpegValid = Resolve<IMediaEncoder>().SetFFmpegPath();
 423
 21424            if (!ffmpegValid)
 425            {
 0426                throw new FfmpegException("Failed to find valid ffmpeg");
 427            }
 428
 21429            Logger.LogInformation("ServerId: {ServerId}", SystemId);
 21430            Logger.LogInformation("Core startup complete");
 21431            CoreStartupHasCompleted = true;
 432
 21433            return Task.CompletedTask;
 434        }
 435
 436        /// <inheritdoc/>
 437        public void Init(IServiceCollection serviceCollection)
 438        {
 21439            DiscoverTypes();
 440
 21441            ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
 442
 21443            NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkMana
 444
 445            // Initialize runtime stat collection
 21446            if (ConfigurationManager.Configuration.EnableMetrics)
 447            {
 0448                _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
 449            }
 450
 21451            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 21452            HttpPort = networkConfiguration.InternalHttpPort;
 21453            HttpsPort = networkConfiguration.InternalHttpsPort;
 454
 455            // Safeguard against invalid configuration
 21456            if (HttpPort == HttpsPort)
 457            {
 0458                HttpPort = NetworkConfiguration.DefaultHttpPort;
 0459                HttpsPort = NetworkConfiguration.DefaultHttpsPort;
 460            }
 461
 21462            CertificatePath = networkConfiguration.CertificatePath;
 21463            Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
 464
 21465            RegisterServices(serviceCollection);
 466
 21467            _pluginManager.RegisterServices(serviceCollection);
 21468        }
 469
 470        /// <summary>
 471        /// Registers services/resources with the service collection that will be available via DI.
 472        /// </summary>
 473        /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
 474        protected virtual void RegisterServices(IServiceCollection serviceCollection)
 475        {
 21476            serviceCollection.AddSingleton(_startupOptions);
 477
 21478            serviceCollection.AddMemoryCache();
 479
 21480            serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
 21481            serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
 21482            serviceCollection.AddSingleton<IApplicationHost>(this);
 21483            serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
 21484            serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
 21485            serviceCollection.AddSingleton<IBackupService, BackupService>();
 486
 21487            serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
 21488            serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
 489
 21490            serviceCollection.AddScoped<ISystemManager, SystemManager>();
 491
 21492            serviceCollection.AddSingleton<TmdbClientManager>();
 21493            serviceCollection.AddSingleton<TmdbMovieSimilarProvider>();
 21494            serviceCollection.AddSingleton<TmdbSeriesSimilarProvider>();
 495
 21496            serviceCollection.AddSingleton<ListenBrainzLabsClient>();
 21497            serviceCollection.AddSingleton<ListenBrainzSimilarArtistProvider>();
 498
 21499            serviceCollection.AddSingleton(NetManager);
 500
 21501            serviceCollection.AddSingleton<ITaskManager, TaskManager>();
 502
 21503            serviceCollection.AddSingleton(_xmlSerializer);
 504
 21505            serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
 506
 21507            serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
 508
 21509            serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
 510
 21511            serviceCollection.AddSingleton<IServerApplicationHost>(this);
 21512            serviceCollection.AddSingleton(ApplicationPaths);
 513
 21514            serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
 515
 21516            serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
 517
 21518            serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
 519
 21520            serviceCollection.AddSingleton<BaseItemRepository>();
 21521            serviceCollection.AddSingleton<IItemRepository>(sp => sp.GetRequiredService<BaseItemRepository>());
 21522            serviceCollection.AddSingleton<IItemQueryHelpers>(sp => sp.GetRequiredService<BaseItemRepository>());
 21523            serviceCollection.AddSingleton<IItemPersistenceService, ItemPersistenceService>();
 21524            serviceCollection.AddSingleton<INextUpService, NextUpService>();
 21525            serviceCollection.AddSingleton<IItemCountService, ItemCountService>();
 21526            serviceCollection.AddSingleton<ILinkedChildrenService, LinkedChildrenService>();
 21527            serviceCollection.AddSingleton<IPeopleRepository, PeopleRepository>();
 21528            serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
 21529            serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
 21530            serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
 21531            serviceCollection.AddSingleton<IKeyframeRepository, KeyframeRepository>();
 21532            serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
 533
 21534            serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
 21535            serviceCollection.AddSingleton<EncodingHelper>();
 21536            serviceCollection.AddSingleton<IPathManager, PathManager>();
 21537            serviceCollection.AddSingleton<IExternalDataManager, ExternalDataManager>();
 538
 539            // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
 21540            serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMon
 21541            serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderM
 21542            serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewM
 21543            serviceCollection.AddTransient(provider => new Lazy<IExternalDataManager>(provider.GetRequiredService<IExter
 21544            serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
 21545            serviceCollection.AddSingleton<NamingOptions>();
 21546            serviceCollection.AddSingleton<VideoListResolver>();
 547
 21548            serviceCollection.AddSingleton<IMusicManager, MusicManager>();
 549
 21550            serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
 21551            serviceCollection.AddSingleton<DotIgnoreIgnoreRule>();
 552
 21553            serviceCollection.AddSingleton<ISimilarItemsManager, SimilarItemsManager>();
 554
 21555            serviceCollection.AddSingleton<ISearchManager, SearchManager>();
 21556            serviceCollection.AddSingleton<ISearchProvider, SqlSearchProvider>();
 557
 21558            serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
 559
 21560            serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
 561
 21562            serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
 563
 21564            serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
 565
 21566            serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
 21567            serviceCollection.AddSingleton<ILyricManager, LyricManager>();
 568
 21569            serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
 570
 571            // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
 21572            serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManag
 21573            serviceCollection.AddSingleton<IDtoService, DtoService>();
 574
 21575            serviceCollection.AddSingleton<ISessionManager, SessionManager>();
 576
 21577            serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
 21578            serviceCollection.AddSingleton<ILimitedConcurrencyLibraryScheduler, LimitedConcurrencyLibraryScheduler>();
 579
 21580            serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
 581
 21582            serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
 583
 21584            serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
 585
 21586            serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
 587
 21588            serviceCollection.AddSingleton<IAuthService, AuthService>();
 21589            serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
 590
 21591            serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
 21592            serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
 21593            serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
 594
 21595            serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtrac
 596
 21597            serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
 21598            serviceCollection.AddScoped<MediaInfoHelper>();
 21599            serviceCollection.AddScoped<AudioHelper>();
 21600            serviceCollection.AddScoped<DynamicHlsHelper>();
 21601            serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
 21602            serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
 603
 21604            serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
 21605        }
 606
 607        /// <summary>
 608        /// Create services registered with the service container that need to be initialized at application startup.
 609        /// </summary>
 610        /// <param name="startupConfig">The configuration used to initialise the application.</param>
 611        /// <returns>A task representing the service initialization operation.</returns>
 612        public async Task InitializeServices(IConfiguration startupConfig)
 613        {
 21614            var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
 21615            await localizationManager.LoadAll().ConfigureAwait(false);
 616
 21617            SetStaticProperties();
 618
 21619            FindParts();
 21620        }
 621
 622        private X509Certificate2 GetCertificate(string path, string password)
 623        {
 21624            if (string.IsNullOrWhiteSpace(path))
 625            {
 21626                return null;
 627            }
 628
 629            try
 630            {
 0631                if (!File.Exists(path))
 632                {
 0633                    return null;
 634                }
 635
 636                // Don't use an empty string password
 0637                password = string.IsNullOrWhiteSpace(password) ? null : password;
 638
 0639                var localCert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.UserKeySet)
 0640                if (!localCert.HasPrivateKey)
 641                {
 0642                    Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
 0643                    return null;
 644                }
 645
 0646                return localCert;
 647            }
 0648            catch (Exception ex)
 649            {
 0650                Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
 0651                return null;
 652            }
 0653        }
 654
 655        /// <summary>
 656        /// Dirty hacks.
 657        /// </summary>
 658        private void SetStaticProperties()
 659        {
 660            // For now there's no real way to inject these properly
 21661            BaseItem.ChapterManager = Resolve<IChapterManager>();
 21662            BaseItem.ChannelManager = Resolve<IChannelManager>();
 21663            BaseItem.ConfigurationManager = ConfigurationManager;
 21664            BaseItem.FileSystem = Resolve<IFileSystem>();
 21665            BaseItem.ItemRepository = Resolve<IItemRepository>();
 21666            BaseItem.ItemCountService = Resolve<IItemCountService>();
 21667            BaseItem.LibraryManager = Resolve<ILibraryManager>();
 21668            BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
 21669            BaseItem.Logger = Resolve<ILogger<BaseItem>>();
 21670            BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
 21671            BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
 21672            BaseItem.ProviderManager = Resolve<IProviderManager>();
 21673            BaseItem.UserDataManager = Resolve<IUserDataManager>();
 21674            CollectionFolder.XmlSerializer = _xmlSerializer;
 21675            CollectionFolder.ApplicationHost = this;
 21676            Folder.UserViewManager = Resolve<IUserViewManager>();
 21677            Folder.CollectionManager = Resolve<ICollectionManager>();
 21678            Folder.LimitedConcurrencyLibraryScheduler = Resolve<ILimitedConcurrencyLibraryScheduler>();
 21679            Episode.MediaEncoder = Resolve<IMediaEncoder>();
 21680            UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
 21681            Video.RecordingsManager = Resolve<IRecordingsManager>();
 21682        }
 683
 684        /// <summary>
 685        /// Finds plugin components and register them with the appropriate services.
 686        /// </summary>
 687        private void FindParts()
 688        {
 21689            if (!ConfigurationManager.Configuration.IsPortAuthorized)
 690            {
 21691                ConfigurationManager.Configuration.IsPortAuthorized = true;
 21692                ConfigurationManager.SaveConfiguration();
 693            }
 694
 21695            _pluginManager.CreatePlugins();
 696
 21697            Resolve<ILibraryManager>().AddParts(
 21698                GetExports<IResolverIgnoreRule>(),
 21699                GetExports<IItemResolver>(),
 21700                GetExports<IIntroProvider>(),
 21701                GetExports<IBaseItemComparer>(),
 21702                GetExports<ILibraryPostScanTask>());
 703
 21704            Resolve<IProviderManager>().AddParts(
 21705                GetExports<IImageProvider>(),
 21706                GetExports<IMetadataService>(),
 21707                GetExports<IMetadataProvider>(),
 21708                GetExports<IMetadataSaver>(),
 21709                GetExports<IExternalId>(),
 21710                GetExports<IExternalUrlProvider>());
 711
 21712            Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
 713
 21714            Resolve<ISimilarItemsManager>().AddParts(GetExports<ISimilarItemsProvider>());
 21715            Resolve<ISearchManager>().AddParts(GetExports<ISearchProvider>());
 21716        }
 717
 718        /// <summary>
 719        /// Discovers the types.
 720        /// </summary>
 721        protected void DiscoverTypes()
 722        {
 21723            Logger.LogInformation("Loading assemblies");
 724
 21725            _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
 21726        }
 727
 728        private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
 729        {
 714730            foreach (var ass in assemblies)
 731            {
 732                Type[] exportedTypes;
 733                try
 734                {
 336735                    exportedTypes = ass.GetExportedTypes();
 336736                }
 0737                catch (FileNotFoundException ex)
 738                {
 0739                    Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
 0740                    _pluginManager.FailPlugin(ass);
 0741                    continue;
 742                }
 0743                catch (TypeLoadException ex)
 744                {
 0745                    Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
 0746                    _pluginManager.FailPlugin(ass);
 0747                    continue;
 748                }
 749
 64050750                foreach (Type type in exportedTypes)
 751                {
 31689752                    if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
 753                    {
 22029754                        yield return type;
 755                    }
 756                }
 757            }
 21758        }
 759
 760        /// <summary>
 761        /// Called when [configuration updated].
 762        /// </summary>
 763        /// <param name="sender">The sender.</param>
 764        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 765        private void OnConfigurationUpdated(object sender, EventArgs e)
 766        {
 18767            var requiresRestart = false;
 18768            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 769
 770            // Don't do anything if these haven't been set yet
 18771            if (HttpPort != 0 && HttpsPort != 0)
 772            {
 773                // Need to restart if ports have changed
 18774                if (networkConfiguration.InternalHttpPort != HttpPort
 18775                    || networkConfiguration.InternalHttpsPort != HttpsPort)
 776                {
 0777                    if (ConfigurationManager.Configuration.IsPortAuthorized)
 778                    {
 0779                        ConfigurationManager.Configuration.IsPortAuthorized = false;
 0780                        ConfigurationManager.SaveConfiguration();
 781
 0782                        requiresRestart = true;
 783                    }
 784                }
 785            }
 786
 18787            if (ValidateSslCertificate(networkConfiguration))
 788            {
 0789                requiresRestart = true;
 790            }
 791
 18792            if (requiresRestart)
 793            {
 0794                Logger.LogInformation("App needs to be restarted due to configuration change.");
 795
 0796                NotifyPendingRestart();
 797            }
 18798        }
 799
 800        /// <summary>
 801        /// Validates the SSL certificate.
 802        /// </summary>
 803        /// <param name="networkConfig">The new configuration.</param>
 804        /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
 805        private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
 806        {
 18807            var newPath = networkConfig.CertificatePath;
 808
 18809            if (!string.IsNullOrWhiteSpace(newPath)
 18810                && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
 811            {
 0812                if (File.Exists(newPath))
 813                {
 0814                    return true;
 815                }
 816
 0817                throw new FileNotFoundException(
 0818                    string.Format(
 0819                        CultureInfo.InvariantCulture,
 0820                        "Certificate file '{0}' does not exist.",
 0821                        newPath));
 822            }
 823
 18824            return false;
 825        }
 826
 827        /// <summary>
 828        /// Notifies the kernel that a change has been made that requires a restart.
 829        /// </summary>
 830        public void NotifyPendingRestart()
 831        {
 0832            Logger.LogInformation("App needs to be restarted.");
 833
 0834            var changed = !HasPendingRestart;
 835
 0836            HasPendingRestart = true;
 837
 0838            if (changed)
 839            {
 0840                EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
 841            }
 0842        }
 843
 844        /// <summary>
 845        /// Gets the composable part assemblies.
 846        /// </summary>
 847        /// <returns>IEnumerable{Assembly}.</returns>
 848        protected IEnumerable<Assembly> GetComposablePartAssemblies()
 849        {
 42850            foreach (var p in _pluginManager.LoadAssemblies())
 851            {
 0852                yield return p;
 853            }
 854
 855            // Include composable parts in the Model assembly
 21856            yield return typeof(SystemInfo).Assembly;
 857
 858            // Include composable parts in the Common assembly
 21859            yield return typeof(IApplicationHost).Assembly;
 860
 861            // Include composable parts in the Controller assembly
 21862            yield return typeof(IServerApplicationHost).Assembly;
 863
 864            // Include composable parts in the Providers assembly
 21865            yield return typeof(ProviderManager).Assembly;
 866
 867            // Include composable parts in the Photos assembly
 21868            yield return typeof(PhotoProvider).Assembly;
 869
 870            // Emby.Server implementations
 21871            yield return typeof(InstallationManager).Assembly;
 872
 873            // MediaEncoding
 21874            yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
 875
 876            // Local metadata
 21877            yield return typeof(BoxSetXmlSaver).Assembly;
 878
 879            // Xbmc
 21880            yield return typeof(ArtistNfoProvider).Assembly;
 881
 882            // Network
 21883            yield return typeof(NetworkManager).Assembly;
 884
 885            // Hls
 21886            yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
 887
 252888            foreach (var i in GetAssembliesWithPartsInternal())
 889            {
 105890                yield return i;
 891            }
 21892        }
 893
 894        protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
 895
 896        /// <inheritdoc/>
 897        public string GetSmartApiUrl(IPAddress remoteAddr)
 898        {
 899            // Published server ends with a /
 0900            if (!string.IsNullOrEmpty(PublishedServerUrl))
 901            {
 902                // Published server ends with a '/', so we need to remove it.
 0903                return PublishedServerUrl.Trim('/');
 904            }
 905
 0906            string smart = NetManager.GetBindAddress(remoteAddr, out var port);
 0907            return GetLocalApiUrl(smart.Trim('/'), null, port);
 908        }
 909
 910        /// <inheritdoc/>
 911        public string GetSmartApiUrl(HttpRequest request)
 912        {
 913            // Return the host in the HTTP request as the API URL if not configured otherwise
 0914            if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
 915            {
 0916                int? requestPort = request.Host.Port;
 0917                if (requestPort is null
 0918                    || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
 0919                    || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)
 920                {
 0921                    requestPort = -1;
 922                }
 923
 0924                return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
 925            }
 926
 0927            return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
 928        }
 929
 930        /// <inheritdoc/>
 931        public string GetSmartApiUrl(string hostname)
 932        {
 933            // Published server ends with a /
 0934            if (!string.IsNullOrEmpty(PublishedServerUrl))
 935            {
 936                // Published server ends with a '/', so we need to remove it.
 0937                return PublishedServerUrl.Trim('/');
 938            }
 939
 0940            string smart = NetManager.GetBindAddress(hostname, out var port);
 0941            return GetLocalApiUrl(smart.Trim('/'), null, port);
 942        }
 943
 944        /// <inheritdoc/>
 945        public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
 946        {
 947            // With an empty source, the port will be null
 0948            var smart = NetManager.GetBindAddress(ipAddress, out _, false);
 0949            var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
 0950            int? port = !allowHttps ? HttpPort : null;
 0951            return GetLocalApiUrl(smart, scheme, port);
 952        }
 953
 954        /// <inheritdoc/>
 955        public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
 956        {
 957            // If the smartAPI doesn't start with http then treat it as a host or ip.
 0958            if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
 959            {
 0960                return hostname.TrimEnd('/');
 961            }
 962
 963            // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
 964            // not. For consistency, always trim the trailing slash.
 0965            scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 0966            var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
 0967            return new UriBuilder
 0968            {
 0969                Scheme = scheme,
 0970                Host = hostname,
 0971                Port = port ?? (isHttps ? HttpsPort : HttpPort),
 0972                Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
 0973            }.ToString().TrimEnd('/');
 974        }
 975
 976        public IEnumerable<Assembly> GetApiPluginAssemblies()
 977        {
 21978            var assemblies = _allConcreteTypes
 21979                .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
 21980                .Select(i => i.Assembly)
 21981                .Distinct();
 982
 126983            foreach (var assembly in assemblies)
 984            {
 42985                Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
 42986                yield return assembly;
 987            }
 21988        }
 989
 990        /// <inheritdoc />
 991        public void Dispose()
 992        {
 21993            Dispose(true);
 21994            GC.SuppressFinalize(this);
 21995        }
 996
 997        /// <summary>
 998        /// Releases unmanaged and - optionally - managed resources.
 999        /// </summary>
 1000        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 1001        protected virtual void Dispose(bool dispose)
 1002        {
 211003            if (_disposed)
 1004            {
 01005                return;
 1006            }
 1007
 211008            if (dispose)
 1009            {
 211010                var type = GetType();
 1011
 211012                Logger.LogInformation("Disposing {Type}", type.Name);
 1013
 841014                foreach (var part in _disposableParts.ToArray())
 1015                {
 211016                    var partType = part.GetType();
 211017                    if (partType == type)
 1018                    {
 1019                        continue;
 1020                    }
 1021
 211022                    Logger.LogInformation("Disposing {Type}", partType.Name);
 1023
 1024                    try
 1025                    {
 211026                        part.Dispose();
 211027                    }
 01028                    catch (Exception ex)
 1029                    {
 01030                        Logger.LogError(ex, "Error disposing {Type}", partType.Name);
 01031                    }
 1032                }
 1033
 211034                _disposableParts.Clear();
 1035
 211036                _pluginManager?.Dispose();
 1037            }
 1038
 211039            _disposed = true;
 211040        }
 1041    }
 1042}