< 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: 282
Uncovered lines: 96
Coverable lines: 378
Total lines: 1038
Line coverage: 74.6%
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 2/13/2026 - 12:11:21 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: 1038 2/13/2026 - 12:11:21 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: 1038

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.SimilarItems;
 30using Emby.Server.Implementations.Localization;
 31using Emby.Server.Implementations.Playlists;
 32using Emby.Server.Implementations.Plugins;
 33using Emby.Server.Implementations.QuickConnect;
 34using Emby.Server.Implementations.ScheduledTasks;
 35using Emby.Server.Implementations.Serialization;
 36using Emby.Server.Implementations.Session;
 37using Emby.Server.Implementations.SyncPlay;
 38using Emby.Server.Implementations.TV;
 39using Emby.Server.Implementations.Updates;
 40using Jellyfin.Api.Helpers;
 41using Jellyfin.Drawing;
 42using Jellyfin.MediaEncoding.Hls.Playlist;
 43using Jellyfin.Networking.Manager;
 44using Jellyfin.Networking.Udp;
 45using Jellyfin.Server.Implementations.FullSystemBackup;
 46using Jellyfin.Server.Implementations.Item;
 47using Jellyfin.Server.Implementations.MediaSegments;
 48using Jellyfin.Server.Implementations.SystemBackupService;
 49using MediaBrowser.Common;
 50using MediaBrowser.Common.Configuration;
 51using MediaBrowser.Common.Events;
 52using MediaBrowser.Common.Net;
 53using MediaBrowser.Common.Plugins;
 54using MediaBrowser.Common.Updates;
 55using MediaBrowser.Controller;
 56using MediaBrowser.Controller.Channels;
 57using MediaBrowser.Controller.Chapters;
 58using MediaBrowser.Controller.ClientEvent;
 59using MediaBrowser.Controller.Collections;
 60using MediaBrowser.Controller.Configuration;
 61using MediaBrowser.Controller.Drawing;
 62using MediaBrowser.Controller.Dto;
 63using MediaBrowser.Controller.Entities;
 64using MediaBrowser.Controller.Entities.TV;
 65using MediaBrowser.Controller.IO;
 66using MediaBrowser.Controller.Library;
 67using MediaBrowser.Controller.LibraryTaskScheduler;
 68using MediaBrowser.Controller.LiveTv;
 69using MediaBrowser.Controller.Lyrics;
 70using MediaBrowser.Controller.MediaEncoding;
 71using MediaBrowser.Controller.MediaSegments;
 72using MediaBrowser.Controller.Net;
 73using MediaBrowser.Controller.Persistence;
 74using MediaBrowser.Controller.Playlists;
 75using MediaBrowser.Controller.Providers;
 76using MediaBrowser.Controller.QuickConnect;
 77using MediaBrowser.Controller.Resolvers;
 78using MediaBrowser.Controller.Session;
 79using MediaBrowser.Controller.Sorting;
 80using MediaBrowser.Controller.Subtitles;
 81using MediaBrowser.Controller.SyncPlay;
 82using MediaBrowser.Controller.TV;
 83using MediaBrowser.LocalMetadata.Savers;
 84using MediaBrowser.MediaEncoding.BdInfo;
 85using MediaBrowser.MediaEncoding.Subtitles;
 86using MediaBrowser.MediaEncoding.Transcoding;
 87using MediaBrowser.Model.Cryptography;
 88using MediaBrowser.Model.Globalization;
 89using MediaBrowser.Model.IO;
 90using MediaBrowser.Model.MediaInfo;
 91using MediaBrowser.Model.Net;
 92using MediaBrowser.Model.Serialization;
 93using MediaBrowser.Model.System;
 94using MediaBrowser.Model.Tasks;
 95using MediaBrowser.Providers.Lyric;
 96using MediaBrowser.Providers.Manager;
 97using MediaBrowser.Providers.Plugins.ListenBrainz;
 98using MediaBrowser.Providers.Plugins.ListenBrainz.Api;
 99using MediaBrowser.Providers.Plugins.Tmdb;
 100using MediaBrowser.Providers.Plugins.Tmdb.Movies;
 101using MediaBrowser.Providers.Plugins.Tmdb.TV;
 102using MediaBrowser.Providers.Subtitles;
 103using MediaBrowser.XbmcMetadata.Providers;
 104using Microsoft.AspNetCore.Http;
 105using Microsoft.AspNetCore.Mvc;
 106using Microsoft.Extensions.Configuration;
 107using Microsoft.Extensions.DependencyInjection;
 108using Microsoft.Extensions.Logging;
 109using Prometheus.DotNetRuntime;
 110using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 111using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
 112using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
 113
 114namespace Emby.Server.Implementations
 115{
 116    /// <summary>
 117    /// Class CompositionRoot.
 118    /// </summary>
 119    public abstract class ApplicationHost : IServerApplicationHost, IDisposable
 120    {
 121        /// <summary>
 122        /// The disposable parts.
 123        /// </summary>
 21124        private readonly ConcurrentBag<IDisposable> _disposableParts = new();
 125        private readonly DeviceId _deviceId;
 126
 127        private readonly IConfiguration _startupConfig;
 128        private readonly IXmlSerializer _xmlSerializer;
 129        private readonly IStartupOptions _startupOptions;
 130        private readonly PluginManager _pluginManager;
 131
 132        private List<Type> _creatingInstances;
 133
 134        /// <summary>
 135        /// Gets or sets all concrete types.
 136        /// </summary>
 137        /// <value>All concrete types.</value>
 138        private Type[] _allConcreteTypes;
 139
 140        private bool _disposed;
 141
 142        /// <summary>
 143        /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
 144        /// </summary>
 145        /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
 146        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
 147        /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
 148        /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
 149        protected ApplicationHost(
 150            IServerApplicationPaths applicationPaths,
 151            ILoggerFactory loggerFactory,
 152            IStartupOptions options,
 153            IConfiguration startupConfig)
 154        {
 155            ApplicationPaths = applicationPaths;
 156            LoggerFactory = loggerFactory;
 21157            _startupOptions = options;
 21158            _startupConfig = startupConfig;
 159
 21160            Logger = LoggerFactory.CreateLogger<ApplicationHost>();
 21161            _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
 162
 21163            ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
 21164            ApplicationVersionString = ApplicationVersion.ToString(3);
 21165            ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
 166
 21167            _xmlSerializer = new MyXmlSerializer();
 21168            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
 21169            _pluginManager = new PluginManager(
 21170                LoggerFactory.CreateLogger<PluginManager>(),
 21171                this,
 21172                ConfigurationManager.Configuration,
 21173                ApplicationPaths.PluginsPath,
 21174                ApplicationVersion);
 21175        }
 176
 177        /// <summary>
 178        /// Occurs when [has pending restart changed].
 179        /// </summary>
 180        public event EventHandler HasPendingRestartChanged;
 181
 182        /// <summary>
 183        /// Gets the value of the PublishedServerUrl setting.
 184        /// </summary>
 0185        private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
 186
 187        public bool CoreStartupHasCompleted { get; private set; }
 188
 189        /// <summary>
 190        /// Gets the <see cref="INetworkManager"/> singleton instance.
 191        /// </summary>
 192        public INetworkManager NetManager { get; private set; }
 193
 194        /// <inheritdoc />
 195        public bool HasPendingRestart { get; private set; }
 196
 197        /// <inheritdoc />
 198        public bool ShouldRestart { get; set; }
 199
 200        /// <summary>
 201        /// Gets the logger.
 202        /// </summary>
 203        protected ILogger<ApplicationHost> Logger { get; }
 204
 205        /// <summary>
 206        /// Gets the logger factory.
 207        /// </summary>
 208        protected ILoggerFactory LoggerFactory { get; }
 209
 210        /// <summary>
 211        /// Gets the application paths.
 212        /// </summary>
 213        /// <value>The application paths.</value>
 214        protected IServerApplicationPaths ApplicationPaths { get; }
 215
 216        /// <summary>
 217        /// Gets the configuration manager.
 218        /// </summary>
 219        /// <value>The configuration manager.</value>
 220        public ServerConfigurationManager ConfigurationManager { get; }
 221
 222        /// <summary>
 223        /// Gets or sets the service provider.
 224        /// </summary>
 225        public IServiceProvider ServiceProvider { get; set; }
 226
 227        /// <summary>
 228        /// Gets the http port for the webhost.
 229        /// </summary>
 230        public int HttpPort { get; private set; }
 231
 232        /// <summary>
 233        /// Gets the https port for the webhost.
 234        /// </summary>
 235        public int HttpsPort { get; private set; }
 236
 237        /// <inheritdoc />
 238        public Version ApplicationVersion { get; }
 239
 240        /// <inheritdoc />
 241        public string ApplicationVersionString { get; }
 242
 243        /// <summary>
 244        /// Gets the current application user agent.
 245        /// </summary>
 246        /// <value>The application user agent.</value>
 247        public string ApplicationUserAgent { get; }
 248
 249        /// <summary>
 250        /// Gets the email address for use within a comment section of a user agent field.
 251        /// Presently used to provide contact information to MusicBrainz service.
 252        /// </summary>
 21253        public string ApplicationUserAgentAddress => "team@jellyfin.org";
 254
 255        /// <summary>
 256        /// Gets the current application name.
 257        /// </summary>
 258        /// <value>The application name.</value>
 21259        public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Locat
 260
 94261        public string SystemId => _deviceId.Value;
 262
 263        /// <inheritdoc/>
 63264        public string Name => ApplicationProductName;
 265
 266        private string CertificatePath { get; set; }
 267
 268        public X509Certificate2 Certificate { get; private set; }
 269
 270        /// <inheritdoc/>
 0271        public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableH
 272
 273        public string FriendlyName =>
 0274            string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
 0275                ? Environment.MachineName
 0276                : ConfigurationManager.Configuration.ServerName;
 277
 278        public string RestoreBackupPath { get; set; }
 279
 280        public string ExpandVirtualPath(string path)
 281        {
 72282            if (path is null)
 283            {
 0284                return null;
 285            }
 286
 72287            var appPaths = ApplicationPaths;
 288
 72289            return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
 72290                .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIg
 291        }
 292
 293        public string ReverseVirtualPath(string path)
 294        {
 111295            var appPaths = ApplicationPaths;
 296
 111297            return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
 111298                .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIg
 299        }
 300
 301        /// <summary>
 302        /// Creates the instance safe.
 303        /// </summary>
 304        /// <param name="type">The type.</param>
 305        /// <returns>System.Object.</returns>
 306        protected object CreateInstanceSafe(Type type)
 307        {
 4536308            _creatingInstances ??= new List<Type>();
 309
 4536310            if (_creatingInstances.Contains(type))
 311            {
 0312                Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
 0313                foreach (var entry in _creatingInstances)
 314                {
 0315                    Logger.LogError("Called from: {TypeName}", entry.FullName);
 316                }
 317
 0318                _pluginManager.FailPlugin(type.Assembly);
 319
 0320                throw new TypeLoadException("DI Loop detected");
 321            }
 322
 323            try
 324            {
 4536325                _creatingInstances.Add(type);
 4536326                Logger.LogDebug("Creating instance of {Type}", type);
 4536327                return ServiceProvider is null
 4536328                    ? Activator.CreateInstance(type)
 4536329                    : ActivatorUtilities.CreateInstance(ServiceProvider, type);
 330            }
 0331            catch (Exception ex)
 332            {
 0333                Logger.LogError(ex, "Error creating {Type}", type);
 334                // If this is a plugin fail it.
 0335                _pluginManager.FailPlugin(type.Assembly);
 0336                return null;
 337            }
 338            finally
 339            {
 4536340                _creatingInstances.Remove(type);
 4536341            }
 4536342        }
 343
 344        /// <summary>
 345        /// Resolves this instance.
 346        /// </summary>
 347        /// <typeparam name="T">The type.</typeparam>
 348        /// <returns>``0.</returns>
 525349        public T Resolve<T>() => ServiceProvider.GetService<T>();
 350
 351        /// <inheritdoc/>
 352        public IEnumerable<Type> GetExportTypes<T>()
 353        {
 399354            var currentType = typeof(T);
 399355            var numberOfConcreteTypes = _allConcreteTypes.Length;
 829920356            for (var i = 0; i < numberOfConcreteTypes; i++)
 357            {
 414561358                var type = _allConcreteTypes[i];
 414561359                if (currentType.IsAssignableFrom(type))
 360                {
 4746361                    yield return type;
 362                }
 363            }
 399364        }
 365
 366        /// <inheritdoc />
 367        public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
 368        {
 369            // Convert to list so this isn't executed for each iteration
 315370            var parts = GetExportTypes<T>()
 315371                .Select(CreateInstanceSafe)
 315372                .Where(i => i is not null)
 315373                .Cast<T>()
 315374                .ToList();
 375
 315376            if (manageLifetime)
 377            {
 588378                foreach (var part in parts.OfType<IDisposable>())
 379                {
 0380                    _disposableParts.Add(part);
 381                }
 382            }
 383
 315384            return parts;
 385        }
 386
 387        /// <inheritdoc />
 388        public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
 389        {
 390            // Convert to list so this isn't executed for each iteration
 21391            var parts = GetExportTypes<T>()
 21392                .Select(i => defaultFunc(i))
 21393                .Where(i => i is not null)
 21394                .Cast<T>()
 21395                .ToList();
 396
 21397            if (manageLifetime)
 398            {
 84399                foreach (var part in parts.OfType<IDisposable>())
 400                {
 21401                    _disposableParts.Add(part);
 402                }
 403            }
 404
 21405            return parts;
 406        }
 407
 408        /// <summary>
 409        /// Runs the startup tasks.
 410        /// </summary>
 411        /// <returns><see cref="Task" />.</returns>
 412        public Task RunStartupTasksAsync()
 413        {
 21414            Logger.LogInformation("Running startup tasks");
 415
 21416            Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
 417
 21418            ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
 21419            ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
 420
 21421            var ffmpegValid = Resolve<IMediaEncoder>().SetFFmpegPath();
 422
 21423            if (!ffmpegValid)
 424            {
 0425                throw new FfmpegException("Failed to find valid ffmpeg");
 426            }
 427
 21428            Logger.LogInformation("ServerId: {ServerId}", SystemId);
 21429            Logger.LogInformation("Core startup complete");
 21430            CoreStartupHasCompleted = true;
 431
 21432            return Task.CompletedTask;
 433        }
 434
 435        /// <inheritdoc/>
 436        public void Init(IServiceCollection serviceCollection)
 437        {
 21438            DiscoverTypes();
 439
 21440            ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
 441
 21442            NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkMana
 443
 444            // Initialize runtime stat collection
 21445            if (ConfigurationManager.Configuration.EnableMetrics)
 446            {
 0447                _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
 448            }
 449
 21450            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 21451            HttpPort = networkConfiguration.InternalHttpPort;
 21452            HttpsPort = networkConfiguration.InternalHttpsPort;
 453
 454            // Safeguard against invalid configuration
 21455            if (HttpPort == HttpsPort)
 456            {
 0457                HttpPort = NetworkConfiguration.DefaultHttpPort;
 0458                HttpsPort = NetworkConfiguration.DefaultHttpsPort;
 459            }
 460
 21461            CertificatePath = networkConfiguration.CertificatePath;
 21462            Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
 463
 21464            RegisterServices(serviceCollection);
 465
 21466            _pluginManager.RegisterServices(serviceCollection);
 21467        }
 468
 469        /// <summary>
 470        /// Registers services/resources with the service collection that will be available via DI.
 471        /// </summary>
 472        /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
 473        protected virtual void RegisterServices(IServiceCollection serviceCollection)
 474        {
 21475            serviceCollection.AddSingleton(_startupOptions);
 476
 21477            serviceCollection.AddMemoryCache();
 478
 21479            serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
 21480            serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
 21481            serviceCollection.AddSingleton<IApplicationHost>(this);
 21482            serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
 21483            serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
 21484            serviceCollection.AddSingleton<IBackupService, BackupService>();
 485
 21486            serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
 21487            serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
 488
 21489            serviceCollection.AddScoped<ISystemManager, SystemManager>();
 490
 21491            serviceCollection.AddSingleton<TmdbClientManager>();
 21492            serviceCollection.AddSingleton<TmdbMovieSimilarProvider>();
 21493            serviceCollection.AddSingleton<TmdbSeriesSimilarProvider>();
 494
 21495            serviceCollection.AddSingleton<ListenBrainzLabsClient>();
 21496            serviceCollection.AddSingleton<ListenBrainzSimilarArtistProvider>();
 497
 21498            serviceCollection.AddSingleton(NetManager);
 499
 21500            serviceCollection.AddSingleton<ITaskManager, TaskManager>();
 501
 21502            serviceCollection.AddSingleton(_xmlSerializer);
 503
 21504            serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
 505
 21506            serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
 507
 21508            serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
 509
 21510            serviceCollection.AddSingleton<IServerApplicationHost>(this);
 21511            serviceCollection.AddSingleton(ApplicationPaths);
 512
 21513            serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
 514
 21515            serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
 516
 21517            serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
 518
 21519            serviceCollection.AddSingleton<BaseItemRepository>();
 21520            serviceCollection.AddSingleton<IItemRepository>(sp => sp.GetRequiredService<BaseItemRepository>());
 21521            serviceCollection.AddSingleton<IItemQueryHelpers>(sp => sp.GetRequiredService<BaseItemRepository>());
 21522            serviceCollection.AddSingleton<IItemPersistenceService, ItemPersistenceService>();
 21523            serviceCollection.AddSingleton<INextUpService, NextUpService>();
 21524            serviceCollection.AddSingleton<IItemCountService, ItemCountService>();
 21525            serviceCollection.AddSingleton<ILinkedChildrenService, LinkedChildrenService>();
 21526            serviceCollection.AddSingleton<IPeopleRepository, PeopleRepository>();
 21527            serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
 21528            serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
 21529            serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
 21530            serviceCollection.AddSingleton<IKeyframeRepository, KeyframeRepository>();
 21531            serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
 532
 21533            serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
 21534            serviceCollection.AddSingleton<EncodingHelper>();
 21535            serviceCollection.AddSingleton<IPathManager, PathManager>();
 21536            serviceCollection.AddSingleton<IExternalDataManager, ExternalDataManager>();
 537
 538            // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
 21539            serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMon
 21540            serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderM
 21541            serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewM
 21542            serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
 21543            serviceCollection.AddSingleton<NamingOptions>();
 21544            serviceCollection.AddSingleton<VideoListResolver>();
 545
 21546            serviceCollection.AddSingleton<IMusicManager, MusicManager>();
 547
 21548            serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
 21549            serviceCollection.AddSingleton<DotIgnoreIgnoreRule>();
 550
 21551            serviceCollection.AddSingleton<ISimilarItemsManager, SimilarItemsManager>();
 552
 21553            serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
 554
 21555            serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
 556
 21557            serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
 558
 21559            serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
 560
 21561            serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
 562
 21563            serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
 21564            serviceCollection.AddSingleton<ILyricManager, LyricManager>();
 565
 21566            serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
 567
 568            // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
 21569            serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManag
 21570            serviceCollection.AddSingleton<IDtoService, DtoService>();
 571
 21572            serviceCollection.AddSingleton<ISessionManager, SessionManager>();
 573
 21574            serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
 21575            serviceCollection.AddSingleton<ILimitedConcurrencyLibraryScheduler, LimitedConcurrencyLibraryScheduler>();
 576
 21577            serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
 578
 21579            serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
 580
 21581            serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
 582
 21583            serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
 584
 21585            serviceCollection.AddSingleton<IAuthService, AuthService>();
 21586            serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
 587
 21588            serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
 21589            serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
 21590            serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
 591
 21592            serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtrac
 593
 21594            serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
 21595            serviceCollection.AddScoped<MediaInfoHelper>();
 21596            serviceCollection.AddScoped<AudioHelper>();
 21597            serviceCollection.AddScoped<DynamicHlsHelper>();
 21598            serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
 21599            serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
 600
 21601            serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
 21602        }
 603
 604        /// <summary>
 605        /// Create services registered with the service container that need to be initialized at application startup.
 606        /// </summary>
 607        /// <param name="startupConfig">The configuration used to initialise the application.</param>
 608        /// <returns>A task representing the service initialization operation.</returns>
 609        public async Task InitializeServices(IConfiguration startupConfig)
 610        {
 21611            var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
 21612            await localizationManager.LoadAll().ConfigureAwait(false);
 613
 21614            SetStaticProperties();
 615
 21616            FindParts();
 21617        }
 618
 619        private X509Certificate2 GetCertificate(string path, string password)
 620        {
 21621            if (string.IsNullOrWhiteSpace(path))
 622            {
 21623                return null;
 624            }
 625
 626            try
 627            {
 0628                if (!File.Exists(path))
 629                {
 0630                    return null;
 631                }
 632
 633                // Don't use an empty string password
 0634                password = string.IsNullOrWhiteSpace(password) ? null : password;
 635
 0636                var localCert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.UserKeySet)
 0637                if (!localCert.HasPrivateKey)
 638                {
 0639                    Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
 0640                    return null;
 641                }
 642
 0643                return localCert;
 644            }
 0645            catch (Exception ex)
 646            {
 0647                Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
 0648                return null;
 649            }
 0650        }
 651
 652        /// <summary>
 653        /// Dirty hacks.
 654        /// </summary>
 655        private void SetStaticProperties()
 656        {
 657            // For now there's no real way to inject these properly
 21658            BaseItem.ChapterManager = Resolve<IChapterManager>();
 21659            BaseItem.ChannelManager = Resolve<IChannelManager>();
 21660            BaseItem.ConfigurationManager = ConfigurationManager;
 21661            BaseItem.FileSystem = Resolve<IFileSystem>();
 21662            BaseItem.ItemRepository = Resolve<IItemRepository>();
 21663            BaseItem.ItemCountService = Resolve<IItemCountService>();
 21664            BaseItem.LibraryManager = Resolve<ILibraryManager>();
 21665            BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
 21666            BaseItem.Logger = Resolve<ILogger<BaseItem>>();
 21667            BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
 21668            BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
 21669            BaseItem.ProviderManager = Resolve<IProviderManager>();
 21670            BaseItem.UserDataManager = Resolve<IUserDataManager>();
 21671            CollectionFolder.XmlSerializer = _xmlSerializer;
 21672            CollectionFolder.ApplicationHost = this;
 21673            Folder.UserViewManager = Resolve<IUserViewManager>();
 21674            Folder.CollectionManager = Resolve<ICollectionManager>();
 21675            Folder.LimitedConcurrencyLibraryScheduler = Resolve<ILimitedConcurrencyLibraryScheduler>();
 21676            Episode.MediaEncoder = Resolve<IMediaEncoder>();
 21677            UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
 21678            Video.RecordingsManager = Resolve<IRecordingsManager>();
 21679        }
 680
 681        /// <summary>
 682        /// Finds plugin components and register them with the appropriate services.
 683        /// </summary>
 684        private void FindParts()
 685        {
 21686            if (!ConfigurationManager.Configuration.IsPortAuthorized)
 687            {
 21688                ConfigurationManager.Configuration.IsPortAuthorized = true;
 21689                ConfigurationManager.SaveConfiguration();
 690            }
 691
 21692            _pluginManager.CreatePlugins();
 693
 21694            Resolve<ILibraryManager>().AddParts(
 21695                GetExports<IResolverIgnoreRule>(),
 21696                GetExports<IItemResolver>(),
 21697                GetExports<IIntroProvider>(),
 21698                GetExports<IBaseItemComparer>(),
 21699                GetExports<ILibraryPostScanTask>());
 700
 21701            Resolve<IProviderManager>().AddParts(
 21702                GetExports<IImageProvider>(),
 21703                GetExports<IMetadataService>(),
 21704                GetExports<IMetadataProvider>(),
 21705                GetExports<IMetadataSaver>(),
 21706                GetExports<IExternalId>(),
 21707                GetExports<IExternalUrlProvider>());
 708
 21709            Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
 710
 21711            Resolve<ISimilarItemsManager>().AddParts(GetExports<ISimilarItemsProvider>());
 21712        }
 713
 714        /// <summary>
 715        /// Discovers the types.
 716        /// </summary>
 717        protected void DiscoverTypes()
 718        {
 21719            Logger.LogInformation("Loading assemblies");
 720
 21721            _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
 21722        }
 723
 724        private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
 725        {
 714726            foreach (var ass in assemblies)
 727            {
 728                Type[] exportedTypes;
 729                try
 730                {
 336731                    exportedTypes = ass.GetExportedTypes();
 336732                }
 0733                catch (FileNotFoundException ex)
 734                {
 0735                    Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
 0736                    _pluginManager.FailPlugin(ass);
 0737                    continue;
 738                }
 0739                catch (TypeLoadException ex)
 740                {
 0741                    Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
 0742                    _pluginManager.FailPlugin(ass);
 0743                    continue;
 744                }
 745
 63378746                foreach (Type type in exportedTypes)
 747                {
 31353748                    if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
 749                    {
 21819750                        yield return type;
 751                    }
 752                }
 753            }
 21754        }
 755
 756        /// <summary>
 757        /// Called when [configuration updated].
 758        /// </summary>
 759        /// <param name="sender">The sender.</param>
 760        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 761        private void OnConfigurationUpdated(object sender, EventArgs e)
 762        {
 18763            var requiresRestart = false;
 18764            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 765
 766            // Don't do anything if these haven't been set yet
 18767            if (HttpPort != 0 && HttpsPort != 0)
 768            {
 769                // Need to restart if ports have changed
 18770                if (networkConfiguration.InternalHttpPort != HttpPort
 18771                    || networkConfiguration.InternalHttpsPort != HttpsPort)
 772                {
 0773                    if (ConfigurationManager.Configuration.IsPortAuthorized)
 774                    {
 0775                        ConfigurationManager.Configuration.IsPortAuthorized = false;
 0776                        ConfigurationManager.SaveConfiguration();
 777
 0778                        requiresRestart = true;
 779                    }
 780                }
 781            }
 782
 18783            if (ValidateSslCertificate(networkConfiguration))
 784            {
 0785                requiresRestart = true;
 786            }
 787
 18788            if (requiresRestart)
 789            {
 0790                Logger.LogInformation("App needs to be restarted due to configuration change.");
 791
 0792                NotifyPendingRestart();
 793            }
 18794        }
 795
 796        /// <summary>
 797        /// Validates the SSL certificate.
 798        /// </summary>
 799        /// <param name="networkConfig">The new configuration.</param>
 800        /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
 801        private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
 802        {
 18803            var newPath = networkConfig.CertificatePath;
 804
 18805            if (!string.IsNullOrWhiteSpace(newPath)
 18806                && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
 807            {
 0808                if (File.Exists(newPath))
 809                {
 0810                    return true;
 811                }
 812
 0813                throw new FileNotFoundException(
 0814                    string.Format(
 0815                        CultureInfo.InvariantCulture,
 0816                        "Certificate file '{0}' does not exist.",
 0817                        newPath));
 818            }
 819
 18820            return false;
 821        }
 822
 823        /// <summary>
 824        /// Notifies the kernel that a change has been made that requires a restart.
 825        /// </summary>
 826        public void NotifyPendingRestart()
 827        {
 0828            Logger.LogInformation("App needs to be restarted.");
 829
 0830            var changed = !HasPendingRestart;
 831
 0832            HasPendingRestart = true;
 833
 0834            if (changed)
 835            {
 0836                EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
 837            }
 0838        }
 839
 840        /// <summary>
 841        /// Gets the composable part assemblies.
 842        /// </summary>
 843        /// <returns>IEnumerable{Assembly}.</returns>
 844        protected IEnumerable<Assembly> GetComposablePartAssemblies()
 845        {
 42846            foreach (var p in _pluginManager.LoadAssemblies())
 847            {
 0848                yield return p;
 849            }
 850
 851            // Include composable parts in the Model assembly
 21852            yield return typeof(SystemInfo).Assembly;
 853
 854            // Include composable parts in the Common assembly
 21855            yield return typeof(IApplicationHost).Assembly;
 856
 857            // Include composable parts in the Controller assembly
 21858            yield return typeof(IServerApplicationHost).Assembly;
 859
 860            // Include composable parts in the Providers assembly
 21861            yield return typeof(ProviderManager).Assembly;
 862
 863            // Include composable parts in the Photos assembly
 21864            yield return typeof(PhotoProvider).Assembly;
 865
 866            // Emby.Server implementations
 21867            yield return typeof(InstallationManager).Assembly;
 868
 869            // MediaEncoding
 21870            yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
 871
 872            // Local metadata
 21873            yield return typeof(BoxSetXmlSaver).Assembly;
 874
 875            // Xbmc
 21876            yield return typeof(ArtistNfoProvider).Assembly;
 877
 878            // Network
 21879            yield return typeof(NetworkManager).Assembly;
 880
 881            // Hls
 21882            yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
 883
 252884            foreach (var i in GetAssembliesWithPartsInternal())
 885            {
 105886                yield return i;
 887            }
 21888        }
 889
 890        protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
 891
 892        /// <inheritdoc/>
 893        public string GetSmartApiUrl(IPAddress remoteAddr)
 894        {
 895            // Published server ends with a /
 0896            if (!string.IsNullOrEmpty(PublishedServerUrl))
 897            {
 898                // Published server ends with a '/', so we need to remove it.
 0899                return PublishedServerUrl.Trim('/');
 900            }
 901
 0902            string smart = NetManager.GetBindAddress(remoteAddr, out var port);
 0903            return GetLocalApiUrl(smart.Trim('/'), null, port);
 904        }
 905
 906        /// <inheritdoc/>
 907        public string GetSmartApiUrl(HttpRequest request)
 908        {
 909            // Return the host in the HTTP request as the API URL if not configured otherwise
 0910            if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
 911            {
 0912                int? requestPort = request.Host.Port;
 0913                if (requestPort is null
 0914                    || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
 0915                    || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)
 916                {
 0917                    requestPort = -1;
 918                }
 919
 0920                return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
 921            }
 922
 0923            return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
 924        }
 925
 926        /// <inheritdoc/>
 927        public string GetSmartApiUrl(string hostname)
 928        {
 929            // Published server ends with a /
 0930            if (!string.IsNullOrEmpty(PublishedServerUrl))
 931            {
 932                // Published server ends with a '/', so we need to remove it.
 0933                return PublishedServerUrl.Trim('/');
 934            }
 935
 0936            string smart = NetManager.GetBindAddress(hostname, out var port);
 0937            return GetLocalApiUrl(smart.Trim('/'), null, port);
 938        }
 939
 940        /// <inheritdoc/>
 941        public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
 942        {
 943            // With an empty source, the port will be null
 0944            var smart = NetManager.GetBindAddress(ipAddress, out _, false);
 0945            var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
 0946            int? port = !allowHttps ? HttpPort : null;
 0947            return GetLocalApiUrl(smart, scheme, port);
 948        }
 949
 950        /// <inheritdoc/>
 951        public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
 952        {
 953            // If the smartAPI doesn't start with http then treat it as a host or ip.
 0954            if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
 955            {
 0956                return hostname.TrimEnd('/');
 957            }
 958
 959            // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
 960            // not. For consistency, always trim the trailing slash.
 0961            scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 0962            var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
 0963            return new UriBuilder
 0964            {
 0965                Scheme = scheme,
 0966                Host = hostname,
 0967                Port = port ?? (isHttps ? HttpsPort : HttpPort),
 0968                Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
 0969            }.ToString().TrimEnd('/');
 970        }
 971
 972        public IEnumerable<Assembly> GetApiPluginAssemblies()
 973        {
 21974            var assemblies = _allConcreteTypes
 21975                .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
 21976                .Select(i => i.Assembly)
 21977                .Distinct();
 978
 126979            foreach (var assembly in assemblies)
 980            {
 42981                Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
 42982                yield return assembly;
 983            }
 21984        }
 985
 986        /// <inheritdoc />
 987        public void Dispose()
 988        {
 21989            Dispose(true);
 21990            GC.SuppressFinalize(this);
 21991        }
 992
 993        /// <summary>
 994        /// Releases unmanaged and - optionally - managed resources.
 995        /// </summary>
 996        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 997        protected virtual void Dispose(bool dispose)
 998        {
 21999            if (_disposed)
 1000            {
 01001                return;
 1002            }
 1003
 211004            if (dispose)
 1005            {
 211006                var type = GetType();
 1007
 211008                Logger.LogInformation("Disposing {Type}", type.Name);
 1009
 841010                foreach (var part in _disposableParts.ToArray())
 1011                {
 211012                    var partType = part.GetType();
 211013                    if (partType == type)
 1014                    {
 1015                        continue;
 1016                    }
 1017
 211018                    Logger.LogInformation("Disposing {Type}", partType.Name);
 1019
 1020                    try
 1021                    {
 211022                        part.Dispose();
 211023                    }
 01024                    catch (Exception ex)
 1025                    {
 01026                        Logger.LogError(ex, "Error disposing {Type}", partType.Name);
 01027                    }
 1028                }
 1029
 211030                _disposableParts.Clear();
 1031
 211032                _pluginManager?.Dispose();
 1033            }
 1034
 211035            _disposed = true;
 211036        }
 1037    }
 1038}