< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.ApplicationHost
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/ApplicationHost.cs
Line coverage
72%
Covered lines: 225
Uncovered lines: 87
Coverable lines: 312
Total lines: 1014
Line coverage: 72.1%
Branch coverage
39%
Covered branches: 41
Total branches: 104
Branch coverage: 39.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

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%
GetExports(...)100%66100%
GetExports(...)83.33%6688.88%
RunStartupTasksAsync()50%2290.9%
Init(...)50%4481.25%
RegisterServices(...)100%11100%
GetCertificate(...)12.5%48814.28%
SetStaticProperties()100%11100%
FindParts()100%22100%
DiscoverTypes()100%11100%
OnConfigurationUpdated(...)64.28%341453.33%
ValidateSslCertificate(...)33.33%15636.36%
NotifyPendingRestart()0%620%
GetSmartApiUrl(...)0%620%
GetSmartApiUrl(...)0%210140%
GetSmartApiUrl(...)0%620%
GetApiUrlForLocalAccess(...)0%2040%
GetLocalApiUrl(...)0%110100%
Dispose()100%11100%
Dispose(...)87.5%9876.47%

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.Photos;
 18using Emby.Server.Implementations.Chapters;
 19using Emby.Server.Implementations.Collections;
 20using Emby.Server.Implementations.Configuration;
 21using Emby.Server.Implementations.Cryptography;
 22using Emby.Server.Implementations.Data;
 23using Emby.Server.Implementations.Devices;
 24using Emby.Server.Implementations.Dto;
 25using Emby.Server.Implementations.HttpServer.Security;
 26using Emby.Server.Implementations.IO;
 27using Emby.Server.Implementations.Library;
 28using Emby.Server.Implementations.Localization;
 29using Emby.Server.Implementations.Playlists;
 30using Emby.Server.Implementations.Plugins;
 31using Emby.Server.Implementations.QuickConnect;
 32using Emby.Server.Implementations.ScheduledTasks;
 33using Emby.Server.Implementations.Serialization;
 34using Emby.Server.Implementations.Session;
 35using Emby.Server.Implementations.SyncPlay;
 36using Emby.Server.Implementations.TV;
 37using Emby.Server.Implementations.Updates;
 38using Jellyfin.Api.Helpers;
 39using Jellyfin.Drawing;
 40using Jellyfin.MediaEncoding.Hls.Playlist;
 41using Jellyfin.Networking.Manager;
 42using Jellyfin.Networking.Udp;
 43using Jellyfin.Server.Implementations.FullSystemBackup;
 44using Jellyfin.Server.Implementations.Item;
 45using Jellyfin.Server.Implementations.MediaSegments;
 46using Jellyfin.Server.Implementations.SystemBackupService;
 47using MediaBrowser.Common;
 48using MediaBrowser.Common.Configuration;
 49using MediaBrowser.Common.Events;
 50using MediaBrowser.Common.Net;
 51using MediaBrowser.Common.Plugins;
 52using MediaBrowser.Common.Updates;
 53using MediaBrowser.Controller;
 54using MediaBrowser.Controller.Channels;
 55using MediaBrowser.Controller.Chapters;
 56using MediaBrowser.Controller.ClientEvent;
 57using MediaBrowser.Controller.Collections;
 58using MediaBrowser.Controller.Configuration;
 59using MediaBrowser.Controller.Drawing;
 60using MediaBrowser.Controller.Dto;
 61using MediaBrowser.Controller.Entities;
 62using MediaBrowser.Controller.Entities.TV;
 63using MediaBrowser.Controller.IO;
 64using MediaBrowser.Controller.Library;
 65using MediaBrowser.Controller.LibraryTaskScheduler;
 66using MediaBrowser.Controller.LiveTv;
 67using MediaBrowser.Controller.Lyrics;
 68using MediaBrowser.Controller.MediaEncoding;
 69using MediaBrowser.Controller.MediaSegments;
 70using MediaBrowser.Controller.Net;
 71using MediaBrowser.Controller.Persistence;
 72using MediaBrowser.Controller.Playlists;
 73using MediaBrowser.Controller.Providers;
 74using MediaBrowser.Controller.QuickConnect;
 75using MediaBrowser.Controller.Resolvers;
 76using MediaBrowser.Controller.Session;
 77using MediaBrowser.Controller.Sorting;
 78using MediaBrowser.Controller.Subtitles;
 79using MediaBrowser.Controller.SyncPlay;
 80using MediaBrowser.Controller.TV;
 81using MediaBrowser.LocalMetadata.Savers;
 82using MediaBrowser.MediaEncoding.BdInfo;
 83using MediaBrowser.MediaEncoding.Subtitles;
 84using MediaBrowser.MediaEncoding.Transcoding;
 85using MediaBrowser.Model.Cryptography;
 86using MediaBrowser.Model.Globalization;
 87using MediaBrowser.Model.IO;
 88using MediaBrowser.Model.MediaInfo;
 89using MediaBrowser.Model.Net;
 90using MediaBrowser.Model.Serialization;
 91using MediaBrowser.Model.System;
 92using MediaBrowser.Model.Tasks;
 93using MediaBrowser.Providers.Lyric;
 94using MediaBrowser.Providers.Manager;
 95using MediaBrowser.Providers.Plugins.Tmdb;
 96using MediaBrowser.Providers.Subtitles;
 97using MediaBrowser.XbmcMetadata.Providers;
 98using Microsoft.AspNetCore.Http;
 99using Microsoft.AspNetCore.Mvc;
 100using Microsoft.Extensions.Configuration;
 101using Microsoft.Extensions.DependencyInjection;
 102using Microsoft.Extensions.Logging;
 103using Prometheus.DotNetRuntime;
 104using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 105using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
 106using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
 107
 108namespace Emby.Server.Implementations
 109{
 110    /// <summary>
 111    /// Class CompositionRoot.
 112    /// </summary>
 113    public abstract class ApplicationHost : IServerApplicationHost, IDisposable
 114    {
 115        /// <summary>
 116        /// The disposable parts.
 117        /// </summary>
 21118        private readonly ConcurrentBag<IDisposable> _disposableParts = new();
 119        private readonly DeviceId _deviceId;
 120
 121        private readonly IConfiguration _startupConfig;
 122        private readonly IXmlSerializer _xmlSerializer;
 123        private readonly IStartupOptions _startupOptions;
 124        private readonly PluginManager _pluginManager;
 125
 126        private List<Type> _creatingInstances;
 127
 128        /// <summary>
 129        /// Gets or sets all concrete types.
 130        /// </summary>
 131        /// <value>All concrete types.</value>
 132        private Type[] _allConcreteTypes;
 133
 134        private bool _disposed;
 135
 136        /// <summary>
 137        /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
 138        /// </summary>
 139        /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
 140        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
 141        /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
 142        /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
 143        protected ApplicationHost(
 144            IServerApplicationPaths applicationPaths,
 145            ILoggerFactory loggerFactory,
 146            IStartupOptions options,
 147            IConfiguration startupConfig)
 148        {
 149            ApplicationPaths = applicationPaths;
 150            LoggerFactory = loggerFactory;
 21151            _startupOptions = options;
 21152            _startupConfig = startupConfig;
 153
 21154            Logger = LoggerFactory.CreateLogger<ApplicationHost>();
 21155            _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
 156
 21157            ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
 21158            ApplicationVersionString = ApplicationVersion.ToString(3);
 21159            ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
 160
 21161            _xmlSerializer = new MyXmlSerializer();
 21162            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
 21163            _pluginManager = new PluginManager(
 21164                LoggerFactory.CreateLogger<PluginManager>(),
 21165                this,
 21166                ConfigurationManager.Configuration,
 21167                ApplicationPaths.PluginsPath,
 21168                ApplicationVersion);
 169
 21170            _disposableParts.Add(_pluginManager);
 21171        }
 172
 173        /// <summary>
 174        /// Occurs when [has pending restart changed].
 175        /// </summary>
 176        public event EventHandler HasPendingRestartChanged;
 177
 178        /// <summary>
 179        /// Gets the value of the PublishedServerUrl setting.
 180        /// </summary>
 0181        private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
 182
 183        public bool CoreStartupHasCompleted { get; private set; }
 184
 185        /// <summary>
 186        /// Gets the <see cref="INetworkManager"/> singleton instance.
 187        /// </summary>
 188        public INetworkManager NetManager { get; private set; }
 189
 190        /// <inheritdoc />
 191        public bool HasPendingRestart { get; private set; }
 192
 193        /// <inheritdoc />
 194        public bool ShouldRestart { get; set; }
 195
 196        /// <summary>
 197        /// Gets the logger.
 198        /// </summary>
 199        protected ILogger<ApplicationHost> Logger { get; }
 200
 201        /// <summary>
 202        /// Gets the logger factory.
 203        /// </summary>
 204        protected ILoggerFactory LoggerFactory { get; }
 205
 206        /// <summary>
 207        /// Gets the application paths.
 208        /// </summary>
 209        /// <value>The application paths.</value>
 210        protected IServerApplicationPaths ApplicationPaths { get; }
 211
 212        /// <summary>
 213        /// Gets the configuration manager.
 214        /// </summary>
 215        /// <value>The configuration manager.</value>
 216        public ServerConfigurationManager ConfigurationManager { get; }
 217
 218        /// <summary>
 219        /// Gets or sets the service provider.
 220        /// </summary>
 221        public IServiceProvider ServiceProvider { get; set; }
 222
 223        /// <summary>
 224        /// Gets the http port for the webhost.
 225        /// </summary>
 226        public int HttpPort { get; private set; }
 227
 228        /// <summary>
 229        /// Gets the https port for the webhost.
 230        /// </summary>
 231        public int HttpsPort { get; private set; }
 232
 233        /// <inheritdoc />
 234        public Version ApplicationVersion { get; }
 235
 236        /// <inheritdoc />
 237        public string ApplicationVersionString { get; }
 238
 239        /// <summary>
 240        /// Gets the current application user agent.
 241        /// </summary>
 242        /// <value>The application user agent.</value>
 243        public string ApplicationUserAgent { get; }
 244
 245        /// <summary>
 246        /// Gets the email address for use within a comment section of a user agent field.
 247        /// Presently used to provide contact information to MusicBrainz service.
 248        /// </summary>
 21249        public string ApplicationUserAgentAddress => "team@jellyfin.org";
 250
 251        /// <summary>
 252        /// Gets the current application name.
 253        /// </summary>
 254        /// <value>The application name.</value>
 21255        public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Locat
 256
 98257        public string SystemId => _deviceId.Value;
 258
 259        /// <inheritdoc/>
 63260        public string Name => ApplicationProductName;
 261
 262        private string CertificatePath { get; set; }
 263
 264        public X509Certificate2 Certificate { get; private set; }
 265
 266        /// <inheritdoc/>
 0267        public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableH
 268
 269        public string FriendlyName =>
 0270            string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
 0271                ? Environment.MachineName
 0272                : ConfigurationManager.Configuration.ServerName;
 273
 274        public string RestoreBackupPath { get; set; }
 275
 276        public string ExpandVirtualPath(string path)
 277        {
 94278            if (path is null)
 279            {
 0280                return null;
 281            }
 282
 94283            var appPaths = ApplicationPaths;
 284
 94285            return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
 94286                .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIg
 287        }
 288
 289        public string ReverseVirtualPath(string path)
 290        {
 85291            var appPaths = ApplicationPaths;
 292
 85293            return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
 85294                .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIg
 295        }
 296
 297        /// <summary>
 298        /// Creates the instance safe.
 299        /// </summary>
 300        /// <param name="type">The type.</param>
 301        /// <returns>System.Object.</returns>
 302        protected object CreateInstanceSafe(Type type)
 303        {
 4137304            _creatingInstances ??= new List<Type>();
 305
 4137306            if (_creatingInstances.Contains(type))
 307            {
 0308                Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
 0309                foreach (var entry in _creatingInstances)
 310                {
 0311                    Logger.LogError("Called from: {TypeName}", entry.FullName);
 312                }
 313
 0314                _pluginManager.FailPlugin(type.Assembly);
 315
 0316                throw new TypeLoadException("DI Loop detected");
 317            }
 318
 319            try
 320            {
 4137321                _creatingInstances.Add(type);
 4137322                Logger.LogDebug("Creating instance of {Type}", type);
 4137323                return ServiceProvider is null
 4137324                    ? Activator.CreateInstance(type)
 4137325                    : ActivatorUtilities.CreateInstance(ServiceProvider, type);
 326            }
 0327            catch (Exception ex)
 328            {
 0329                Logger.LogError(ex, "Error creating {Type}", type);
 330                // If this is a plugin fail it.
 0331                _pluginManager.FailPlugin(type.Assembly);
 0332                return null;
 333            }
 334            finally
 335            {
 4137336                _creatingInstances.Remove(type);
 4137337            }
 4137338        }
 339
 340        /// <summary>
 341        /// Resolves this instance.
 342        /// </summary>
 343        /// <typeparam name="T">The type.</typeparam>
 344        /// <returns>``0.</returns>
 483345        public T Resolve<T>() => ServiceProvider.GetService<T>();
 346
 347        /// <inheritdoc/>
 348        public IEnumerable<Type> GetExportTypes<T>()
 349        {
 350            var currentType = typeof(T);
 351            var numberOfConcreteTypes = _allConcreteTypes.Length;
 352            for (var i = 0; i < numberOfConcreteTypes; i++)
 353            {
 354                var type = _allConcreteTypes[i];
 355                if (currentType.IsAssignableFrom(type))
 356                {
 357                    yield return type;
 358                }
 359            }
 360        }
 361
 362        /// <inheritdoc />
 363        public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
 364        {
 365            // Convert to list so this isn't executed for each iteration
 294366            var parts = GetExportTypes<T>()
 294367                .Select(CreateInstanceSafe)
 294368                .Where(i => i is not null)
 294369                .Cast<T>()
 294370                .ToList();
 371
 294372            if (manageLifetime)
 373            {
 630374                foreach (var part in parts.OfType<IDisposable>())
 375                {
 42376                    _disposableParts.Add(part);
 377                }
 378            }
 379
 294380            return parts;
 381        }
 382
 383        /// <inheritdoc />
 384        public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
 385        {
 386            // Convert to list so this isn't executed for each iteration
 21387            var parts = GetExportTypes<T>()
 21388                .Select(i => defaultFunc(i))
 21389                .Where(i => i is not null)
 21390                .Cast<T>()
 21391                .ToList();
 392
 21393            if (manageLifetime)
 394            {
 42395                foreach (var part in parts.OfType<IDisposable>())
 396                {
 0397                    _disposableParts.Add(part);
 398                }
 399            }
 400
 21401            return parts;
 402        }
 403
 404        /// <summary>
 405        /// Runs the startup tasks.
 406        /// </summary>
 407        /// <returns><see cref="Task" />.</returns>
 408        public Task RunStartupTasksAsync()
 409        {
 21410            Logger.LogInformation("Running startup tasks");
 411
 21412            Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
 413
 21414            ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
 21415            ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
 416
 21417            var ffmpegValid = Resolve<IMediaEncoder>().SetFFmpegPath();
 418
 21419            if (!ffmpegValid)
 420            {
 0421                throw new FfmpegException("Failed to find valid ffmpeg");
 422            }
 423
 21424            Logger.LogInformation("ServerId: {ServerId}", SystemId);
 21425            Logger.LogInformation("Core startup complete");
 21426            CoreStartupHasCompleted = true;
 427
 21428            return Task.CompletedTask;
 429        }
 430
 431        /// <inheritdoc/>
 432        public void Init(IServiceCollection serviceCollection)
 433        {
 21434            DiscoverTypes();
 435
 21436            ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
 437
 21438            NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkMana
 439
 440            // Initialize runtime stat collection
 21441            if (ConfigurationManager.Configuration.EnableMetrics)
 442            {
 0443                _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
 444            }
 445
 21446            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 21447            HttpPort = networkConfiguration.InternalHttpPort;
 21448            HttpsPort = networkConfiguration.InternalHttpsPort;
 449
 450            // Safeguard against invalid configuration
 21451            if (HttpPort == HttpsPort)
 452            {
 0453                HttpPort = NetworkConfiguration.DefaultHttpPort;
 0454                HttpsPort = NetworkConfiguration.DefaultHttpsPort;
 455            }
 456
 21457            CertificatePath = networkConfiguration.CertificatePath;
 21458            Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
 459
 21460            RegisterServices(serviceCollection);
 461
 21462            _pluginManager.RegisterServices(serviceCollection);
 21463        }
 464
 465        /// <summary>
 466        /// Registers services/resources with the service collection that will be available via DI.
 467        /// </summary>
 468        /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
 469        protected virtual void RegisterServices(IServiceCollection serviceCollection)
 470        {
 21471            serviceCollection.AddSingleton(_startupOptions);
 472
 21473            serviceCollection.AddMemoryCache();
 474
 21475            serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
 21476            serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
 21477            serviceCollection.AddSingleton<IApplicationHost>(this);
 21478            serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
 21479            serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
 21480            serviceCollection.AddSingleton<IBackupService, BackupService>();
 481
 21482            serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
 21483            serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
 484
 21485            serviceCollection.AddScoped<ISystemManager, SystemManager>();
 486
 21487            serviceCollection.AddSingleton<TmdbClientManager>();
 488
 21489            serviceCollection.AddSingleton(NetManager);
 490
 21491            serviceCollection.AddSingleton<ITaskManager, TaskManager>();
 492
 21493            serviceCollection.AddSingleton(_xmlSerializer);
 494
 21495            serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
 496
 21497            serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
 498
 21499            serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
 500
 21501            serviceCollection.AddSingleton<IServerApplicationHost>(this);
 21502            serviceCollection.AddSingleton(ApplicationPaths);
 503
 21504            serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
 505
 21506            serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
 507
 21508            serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
 509
 21510            serviceCollection.AddSingleton<IItemRepository, BaseItemRepository>();
 21511            serviceCollection.AddSingleton<IPeopleRepository, PeopleRepository>();
 21512            serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
 21513            serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
 21514            serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
 21515            serviceCollection.AddSingleton<IKeyframeRepository, KeyframeRepository>();
 21516            serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
 517
 21518            serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
 21519            serviceCollection.AddSingleton<EncodingHelper>();
 21520            serviceCollection.AddSingleton<IPathManager, PathManager>();
 21521            serviceCollection.AddSingleton<IExternalDataManager, ExternalDataManager>();
 522
 523            // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
 21524            serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMon
 21525            serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderM
 21526            serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewM
 21527            serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
 21528            serviceCollection.AddSingleton<NamingOptions>();
 529
 21530            serviceCollection.AddSingleton<IMusicManager, MusicManager>();
 531
 21532            serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
 533
 21534            serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
 535
 21536            serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
 537
 21538            serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
 539
 21540            serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
 541
 21542            serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
 543
 21544            serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
 21545            serviceCollection.AddSingleton<ILyricManager, LyricManager>();
 546
 21547            serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
 548
 549            // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
 21550            serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManag
 21551            serviceCollection.AddSingleton<IDtoService, DtoService>();
 552
 21553            serviceCollection.AddSingleton<ISessionManager, SessionManager>();
 554
 21555            serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
 21556            serviceCollection.AddSingleton<ILimitedConcurrencyLibraryScheduler, LimitedConcurrencyLibraryScheduler>();
 557
 21558            serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
 559
 21560            serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
 561
 21562            serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
 563
 21564            serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
 565
 21566            serviceCollection.AddSingleton<IAuthService, AuthService>();
 21567            serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
 568
 21569            serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
 21570            serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
 21571            serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
 572
 21573            serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtrac
 574
 21575            serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
 21576            serviceCollection.AddScoped<MediaInfoHelper>();
 21577            serviceCollection.AddScoped<AudioHelper>();
 21578            serviceCollection.AddScoped<DynamicHlsHelper>();
 21579            serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
 21580            serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
 581
 21582            serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
 21583        }
 584
 585        /// <summary>
 586        /// Create services registered with the service container that need to be initialized at application startup.
 587        /// </summary>
 588        /// <param name="startupConfig">The configuration used to initialise the application.</param>
 589        /// <returns>A task representing the service initialization operation.</returns>
 590        public async Task InitializeServices(IConfiguration startupConfig)
 591        {
 592            var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
 593            await localizationManager.LoadAll().ConfigureAwait(false);
 594
 595            SetStaticProperties();
 596
 597            FindParts();
 598        }
 599
 600        private X509Certificate2 GetCertificate(string path, string password)
 601        {
 21602            if (string.IsNullOrWhiteSpace(path))
 603            {
 21604                return null;
 605            }
 606
 607            try
 608            {
 0609                if (!File.Exists(path))
 610                {
 0611                    return null;
 612                }
 613
 614                // Don't use an empty string password
 0615                password = string.IsNullOrWhiteSpace(password) ? null : password;
 616
 0617                var localCert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.UserKeySet)
 0618                if (!localCert.HasPrivateKey)
 619                {
 0620                    Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
 0621                    return null;
 622                }
 623
 0624                return localCert;
 625            }
 0626            catch (Exception ex)
 627            {
 0628                Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
 0629                return null;
 630            }
 0631        }
 632
 633        /// <summary>
 634        /// Dirty hacks.
 635        /// </summary>
 636        private void SetStaticProperties()
 637        {
 638            // For now there's no real way to inject these properly
 21639            BaseItem.ChapterManager = Resolve<IChapterManager>();
 21640            BaseItem.ChannelManager = Resolve<IChannelManager>();
 21641            BaseItem.ConfigurationManager = ConfigurationManager;
 21642            BaseItem.FileSystem = Resolve<IFileSystem>();
 21643            BaseItem.ItemRepository = Resolve<IItemRepository>();
 21644            BaseItem.LibraryManager = Resolve<ILibraryManager>();
 21645            BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
 21646            BaseItem.Logger = Resolve<ILogger<BaseItem>>();
 21647            BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
 21648            BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
 21649            BaseItem.ProviderManager = Resolve<IProviderManager>();
 21650            BaseItem.UserDataManager = Resolve<IUserDataManager>();
 21651            CollectionFolder.XmlSerializer = _xmlSerializer;
 21652            CollectionFolder.ApplicationHost = this;
 21653            Folder.UserViewManager = Resolve<IUserViewManager>();
 21654            Folder.CollectionManager = Resolve<ICollectionManager>();
 21655            Folder.LimitedConcurrencyLibraryScheduler = Resolve<ILimitedConcurrencyLibraryScheduler>();
 21656            Episode.MediaEncoder = Resolve<IMediaEncoder>();
 21657            UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
 21658            Video.RecordingsManager = Resolve<IRecordingsManager>();
 21659        }
 660
 661        /// <summary>
 662        /// Finds plugin components and register them with the appropriate services.
 663        /// </summary>
 664        private void FindParts()
 665        {
 21666            if (!ConfigurationManager.Configuration.IsPortAuthorized)
 667            {
 21668                ConfigurationManager.Configuration.IsPortAuthorized = true;
 21669                ConfigurationManager.SaveConfiguration();
 670            }
 671
 21672            _pluginManager.CreatePlugins();
 673
 21674            Resolve<ILibraryManager>().AddParts(
 21675                GetExports<IResolverIgnoreRule>(),
 21676                GetExports<IItemResolver>(),
 21677                GetExports<IIntroProvider>(),
 21678                GetExports<IBaseItemComparer>(),
 21679                GetExports<ILibraryPostScanTask>());
 680
 21681            Resolve<IProviderManager>().AddParts(
 21682                GetExports<IImageProvider>(),
 21683                GetExports<IMetadataService>(),
 21684                GetExports<IMetadataProvider>(),
 21685                GetExports<IMetadataSaver>(),
 21686                GetExports<IExternalId>(),
 21687                GetExports<IExternalUrlProvider>());
 688
 21689            Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
 21690        }
 691
 692        /// <summary>
 693        /// Discovers the types.
 694        /// </summary>
 695        protected void DiscoverTypes()
 696        {
 21697            Logger.LogInformation("Loading assemblies");
 698
 21699            _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
 21700        }
 701
 702        private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
 703        {
 704            foreach (var ass in assemblies)
 705            {
 706                Type[] exportedTypes;
 707                try
 708                {
 709                    exportedTypes = ass.GetExportedTypes();
 710                }
 711                catch (FileNotFoundException ex)
 712                {
 713                    Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
 714                    _pluginManager.FailPlugin(ass);
 715                    continue;
 716                }
 717                catch (TypeLoadException ex)
 718                {
 719                    Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
 720                    _pluginManager.FailPlugin(ass);
 721                    continue;
 722                }
 723
 724                foreach (Type type in exportedTypes)
 725                {
 726                    if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
 727                    {
 728                        yield return type;
 729                    }
 730                }
 731            }
 732        }
 733
 734        /// <summary>
 735        /// Called when [configuration updated].
 736        /// </summary>
 737        /// <param name="sender">The sender.</param>
 738        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 739        private void OnConfigurationUpdated(object sender, EventArgs e)
 740        {
 18741            var requiresRestart = false;
 18742            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 743
 744            // Don't do anything if these haven't been set yet
 18745            if (HttpPort != 0 && HttpsPort != 0)
 746            {
 747                // Need to restart if ports have changed
 18748                if (networkConfiguration.InternalHttpPort != HttpPort
 18749                    || networkConfiguration.InternalHttpsPort != HttpsPort)
 750                {
 0751                    if (ConfigurationManager.Configuration.IsPortAuthorized)
 752                    {
 0753                        ConfigurationManager.Configuration.IsPortAuthorized = false;
 0754                        ConfigurationManager.SaveConfiguration();
 755
 0756                        requiresRestart = true;
 757                    }
 758                }
 759            }
 760
 18761            if (ValidateSslCertificate(networkConfiguration))
 762            {
 0763                requiresRestart = true;
 764            }
 765
 18766            if (requiresRestart)
 767            {
 0768                Logger.LogInformation("App needs to be restarted due to configuration change.");
 769
 0770                NotifyPendingRestart();
 771            }
 18772        }
 773
 774        /// <summary>
 775        /// Validates the SSL certificate.
 776        /// </summary>
 777        /// <param name="networkConfig">The new configuration.</param>
 778        /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
 779        private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
 780        {
 18781            var newPath = networkConfig.CertificatePath;
 782
 18783            if (!string.IsNullOrWhiteSpace(newPath)
 18784                && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
 785            {
 0786                if (File.Exists(newPath))
 787                {
 0788                    return true;
 789                }
 790
 0791                throw new FileNotFoundException(
 0792                    string.Format(
 0793                        CultureInfo.InvariantCulture,
 0794                        "Certificate file '{0}' does not exist.",
 0795                        newPath));
 796            }
 797
 18798            return false;
 799        }
 800
 801        /// <summary>
 802        /// Notifies the kernel that a change has been made that requires a restart.
 803        /// </summary>
 804        public void NotifyPendingRestart()
 805        {
 0806            Logger.LogInformation("App needs to be restarted.");
 807
 0808            var changed = !HasPendingRestart;
 809
 0810            HasPendingRestart = true;
 811
 0812            if (changed)
 813            {
 0814                EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
 815            }
 0816        }
 817
 818        /// <summary>
 819        /// Gets the composable part assemblies.
 820        /// </summary>
 821        /// <returns>IEnumerable{Assembly}.</returns>
 822        protected IEnumerable<Assembly> GetComposablePartAssemblies()
 823        {
 824            foreach (var p in _pluginManager.LoadAssemblies())
 825            {
 826                yield return p;
 827            }
 828
 829            // Include composable parts in the Model assembly
 830            yield return typeof(SystemInfo).Assembly;
 831
 832            // Include composable parts in the Common assembly
 833            yield return typeof(IApplicationHost).Assembly;
 834
 835            // Include composable parts in the Controller assembly
 836            yield return typeof(IServerApplicationHost).Assembly;
 837
 838            // Include composable parts in the Providers assembly
 839            yield return typeof(ProviderManager).Assembly;
 840
 841            // Include composable parts in the Photos assembly
 842            yield return typeof(PhotoProvider).Assembly;
 843
 844            // Emby.Server implementations
 845            yield return typeof(InstallationManager).Assembly;
 846
 847            // MediaEncoding
 848            yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
 849
 850            // Local metadata
 851            yield return typeof(BoxSetXmlSaver).Assembly;
 852
 853            // Xbmc
 854            yield return typeof(ArtistNfoProvider).Assembly;
 855
 856            // Network
 857            yield return typeof(NetworkManager).Assembly;
 858
 859            // Hls
 860            yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
 861
 862            foreach (var i in GetAssembliesWithPartsInternal())
 863            {
 864                yield return i;
 865            }
 866        }
 867
 868        protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
 869
 870        /// <inheritdoc/>
 871        public string GetSmartApiUrl(IPAddress remoteAddr)
 872        {
 873            // Published server ends with a /
 0874            if (!string.IsNullOrEmpty(PublishedServerUrl))
 875            {
 876                // Published server ends with a '/', so we need to remove it.
 0877                return PublishedServerUrl.Trim('/');
 878            }
 879
 0880            string smart = NetManager.GetBindAddress(remoteAddr, out var port);
 0881            return GetLocalApiUrl(smart.Trim('/'), null, port);
 882        }
 883
 884        /// <inheritdoc/>
 885        public string GetSmartApiUrl(HttpRequest request)
 886        {
 887            // Return the host in the HTTP request as the API URL if not configured otherwise
 0888            if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
 889            {
 0890                int? requestPort = request.Host.Port;
 0891                if (requestPort is null
 0892                    || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
 0893                    || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)
 894                {
 0895                    requestPort = -1;
 896                }
 897
 0898                return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
 899            }
 900
 0901            return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
 902        }
 903
 904        /// <inheritdoc/>
 905        public string GetSmartApiUrl(string hostname)
 906        {
 907            // Published server ends with a /
 0908            if (!string.IsNullOrEmpty(PublishedServerUrl))
 909            {
 910                // Published server ends with a '/', so we need to remove it.
 0911                return PublishedServerUrl.Trim('/');
 912            }
 913
 0914            string smart = NetManager.GetBindAddress(hostname, out var port);
 0915            return GetLocalApiUrl(smart.Trim('/'), null, port);
 916        }
 917
 918        /// <inheritdoc/>
 919        public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
 920        {
 921            // With an empty source, the port will be null
 0922            var smart = NetManager.GetBindAddress(ipAddress, out _, false);
 0923            var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
 0924            int? port = !allowHttps ? HttpPort : null;
 0925            return GetLocalApiUrl(smart, scheme, port);
 926        }
 927
 928        /// <inheritdoc/>
 929        public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
 930        {
 931            // If the smartAPI doesn't start with http then treat it as a host or ip.
 0932            if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
 933            {
 0934                return hostname.TrimEnd('/');
 935            }
 936
 937            // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
 938            // not. For consistency, always trim the trailing slash.
 0939            scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 0940            var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
 0941            return new UriBuilder
 0942            {
 0943                Scheme = scheme,
 0944                Host = hostname,
 0945                Port = port ?? (isHttps ? HttpsPort : HttpPort),
 0946                Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
 0947            }.ToString().TrimEnd('/');
 948        }
 949
 950        public IEnumerable<Assembly> GetApiPluginAssemblies()
 951        {
 952            var assemblies = _allConcreteTypes
 953                .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
 954                .Select(i => i.Assembly)
 955                .Distinct();
 956
 957            foreach (var assembly in assemblies)
 958            {
 959                Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
 960                yield return assembly;
 961            }
 962        }
 963
 964        /// <inheritdoc />
 965        public void Dispose()
 966        {
 21967            Dispose(true);
 21968            GC.SuppressFinalize(this);
 21969        }
 970
 971        /// <summary>
 972        /// Releases unmanaged and - optionally - managed resources.
 973        /// </summary>
 974        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 975        protected virtual void Dispose(bool dispose)
 976        {
 21977            if (_disposed)
 978            {
 0979                return;
 980            }
 981
 21982            if (dispose)
 983            {
 21984                var type = GetType();
 985
 21986                Logger.LogInformation("Disposing {Type}", type.Name);
 987
 168988                foreach (var part in _disposableParts.ToArray())
 989                {
 63990                    var partType = part.GetType();
 63991                    if (partType == type)
 992                    {
 993                        continue;
 994                    }
 995
 63996                    Logger.LogInformation("Disposing {Type}", partType.Name);
 997
 998                    try
 999                    {
 631000                        part.Dispose();
 631001                    }
 01002                    catch (Exception ex)
 1003                    {
 01004                        Logger.LogError(ex, "Error disposing {Type}", partType.Name);
 01005                    }
 1006                }
 1007
 211008                _disposableParts.Clear();
 1009            }
 1010
 211011            _disposed = true;
 211012        }
 1013    }
 1014}