< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.ApplicationHost
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/ApplicationHost.cs
Line coverage
71%
Covered lines: 222
Uncovered lines: 87
Coverable lines: 309
Total lines: 1006
Line coverage: 71.8%
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.Item;
 44using Jellyfin.Server.Implementations.MediaSegments;
 45using MediaBrowser.Common;
 46using MediaBrowser.Common.Configuration;
 47using MediaBrowser.Common.Events;
 48using MediaBrowser.Common.Net;
 49using MediaBrowser.Common.Plugins;
 50using MediaBrowser.Common.Updates;
 51using MediaBrowser.Controller;
 52using MediaBrowser.Controller.Channels;
 53using MediaBrowser.Controller.Chapters;
 54using MediaBrowser.Controller.ClientEvent;
 55using MediaBrowser.Controller.Collections;
 56using MediaBrowser.Controller.Configuration;
 57using MediaBrowser.Controller.Drawing;
 58using MediaBrowser.Controller.Dto;
 59using MediaBrowser.Controller.Entities;
 60using MediaBrowser.Controller.Entities.TV;
 61using MediaBrowser.Controller.IO;
 62using MediaBrowser.Controller.Library;
 63using MediaBrowser.Controller.LiveTv;
 64using MediaBrowser.Controller.Lyrics;
 65using MediaBrowser.Controller.MediaEncoding;
 66using MediaBrowser.Controller.MediaSegments;
 67using MediaBrowser.Controller.Net;
 68using MediaBrowser.Controller.Persistence;
 69using MediaBrowser.Controller.Playlists;
 70using MediaBrowser.Controller.Providers;
 71using MediaBrowser.Controller.QuickConnect;
 72using MediaBrowser.Controller.Resolvers;
 73using MediaBrowser.Controller.Session;
 74using MediaBrowser.Controller.Sorting;
 75using MediaBrowser.Controller.Subtitles;
 76using MediaBrowser.Controller.SyncPlay;
 77using MediaBrowser.Controller.TV;
 78using MediaBrowser.LocalMetadata.Savers;
 79using MediaBrowser.MediaEncoding.BdInfo;
 80using MediaBrowser.MediaEncoding.Subtitles;
 81using MediaBrowser.MediaEncoding.Transcoding;
 82using MediaBrowser.Model.Cryptography;
 83using MediaBrowser.Model.Globalization;
 84using MediaBrowser.Model.IO;
 85using MediaBrowser.Model.MediaInfo;
 86using MediaBrowser.Model.Net;
 87using MediaBrowser.Model.Serialization;
 88using MediaBrowser.Model.System;
 89using MediaBrowser.Model.Tasks;
 90using MediaBrowser.Providers.Lyric;
 91using MediaBrowser.Providers.Manager;
 92using MediaBrowser.Providers.Plugins.Tmdb;
 93using MediaBrowser.Providers.Subtitles;
 94using MediaBrowser.XbmcMetadata.Providers;
 95using Microsoft.AspNetCore.Http;
 96using Microsoft.AspNetCore.Mvc;
 97using Microsoft.Extensions.Configuration;
 98using Microsoft.Extensions.DependencyInjection;
 99using Microsoft.Extensions.Logging;
 100using Prometheus.DotNetRuntime;
 101using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 102using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
 103using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
 104
 105namespace Emby.Server.Implementations
 106{
 107    /// <summary>
 108    /// Class CompositionRoot.
 109    /// </summary>
 110    public abstract class ApplicationHost : IServerApplicationHost, IDisposable
 111    {
 112        /// <summary>
 113        /// The disposable parts.
 114        /// </summary>
 21115        private readonly ConcurrentBag<IDisposable> _disposableParts = new();
 116        private readonly DeviceId _deviceId;
 117
 118        private readonly IConfiguration _startupConfig;
 119        private readonly IXmlSerializer _xmlSerializer;
 120        private readonly IStartupOptions _startupOptions;
 121        private readonly PluginManager _pluginManager;
 122
 123        private List<Type> _creatingInstances;
 124
 125        /// <summary>
 126        /// Gets or sets all concrete types.
 127        /// </summary>
 128        /// <value>All concrete types.</value>
 129        private Type[] _allConcreteTypes;
 130
 131        private bool _disposed;
 132
 133        /// <summary>
 134        /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
 135        /// </summary>
 136        /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
 137        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
 138        /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
 139        /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
 140        protected ApplicationHost(
 141            IServerApplicationPaths applicationPaths,
 142            ILoggerFactory loggerFactory,
 143            IStartupOptions options,
 144            IConfiguration startupConfig)
 145        {
 146            ApplicationPaths = applicationPaths;
 147            LoggerFactory = loggerFactory;
 21148            _startupOptions = options;
 21149            _startupConfig = startupConfig;
 150
 21151            Logger = LoggerFactory.CreateLogger<ApplicationHost>();
 21152            _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
 153
 21154            ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
 21155            ApplicationVersionString = ApplicationVersion.ToString(3);
 21156            ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
 157
 21158            _xmlSerializer = new MyXmlSerializer();
 21159            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
 21160            _pluginManager = new PluginManager(
 21161                LoggerFactory.CreateLogger<PluginManager>(),
 21162                this,
 21163                ConfigurationManager.Configuration,
 21164                ApplicationPaths.PluginsPath,
 21165                ApplicationVersion);
 166
 21167            _disposableParts.Add(_pluginManager);
 21168        }
 169
 170        /// <summary>
 171        /// Occurs when [has pending restart changed].
 172        /// </summary>
 173        public event EventHandler HasPendingRestartChanged;
 174
 175        /// <summary>
 176        /// Gets the value of the PublishedServerUrl setting.
 177        /// </summary>
 0178        private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
 179
 180        public bool CoreStartupHasCompleted { get; private set; }
 181
 182        /// <summary>
 183        /// Gets the <see cref="INetworkManager"/> singleton instance.
 184        /// </summary>
 185        public INetworkManager NetManager { get; private set; }
 186
 187        /// <inheritdoc />
 188        public bool HasPendingRestart { get; private set; }
 189
 190        /// <inheritdoc />
 191        public bool ShouldRestart { get; set; }
 192
 193        /// <summary>
 194        /// Gets the logger.
 195        /// </summary>
 196        protected ILogger<ApplicationHost> Logger { get; }
 197
 198        /// <summary>
 199        /// Gets the logger factory.
 200        /// </summary>
 201        protected ILoggerFactory LoggerFactory { get; }
 202
 203        /// <summary>
 204        /// Gets the application paths.
 205        /// </summary>
 206        /// <value>The application paths.</value>
 207        protected IServerApplicationPaths ApplicationPaths { get; }
 208
 209        /// <summary>
 210        /// Gets the configuration manager.
 211        /// </summary>
 212        /// <value>The configuration manager.</value>
 213        public ServerConfigurationManager ConfigurationManager { get; }
 214
 215        /// <summary>
 216        /// Gets or sets the service provider.
 217        /// </summary>
 218        public IServiceProvider ServiceProvider { get; set; }
 219
 220        /// <summary>
 221        /// Gets the http port for the webhost.
 222        /// </summary>
 223        public int HttpPort { get; private set; }
 224
 225        /// <summary>
 226        /// Gets the https port for the webhost.
 227        /// </summary>
 228        public int HttpsPort { get; private set; }
 229
 230        /// <inheritdoc />
 231        public Version ApplicationVersion { get; }
 232
 233        /// <inheritdoc />
 234        public string ApplicationVersionString { get; }
 235
 236        /// <summary>
 237        /// Gets the current application user agent.
 238        /// </summary>
 239        /// <value>The application user agent.</value>
 240        public string ApplicationUserAgent { get; }
 241
 242        /// <summary>
 243        /// Gets the email address for use within a comment section of a user agent field.
 244        /// Presently used to provide contact information to MusicBrainz service.
 245        /// </summary>
 21246        public string ApplicationUserAgentAddress => "team@jellyfin.org";
 247
 248        /// <summary>
 249        /// Gets the current application name.
 250        /// </summary>
 251        /// <value>The application name.</value>
 21252        public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Locat
 253
 98254        public string SystemId => _deviceId.Value;
 255
 256        /// <inheritdoc/>
 63257        public string Name => ApplicationProductName;
 258
 259        private string CertificatePath { get; set; }
 260
 261        public X509Certificate2 Certificate { get; private set; }
 262
 263        /// <inheritdoc/>
 0264        public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableH
 265
 266        public string FriendlyName =>
 0267            string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
 0268                ? Environment.MachineName
 0269                : ConfigurationManager.Configuration.ServerName;
 270
 271        public string ExpandVirtualPath(string path)
 272        {
 86273            if (path is null)
 274            {
 0275                return null;
 276            }
 277
 86278            var appPaths = ApplicationPaths;
 279
 86280            return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
 86281                .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIg
 282        }
 283
 284        public string ReverseVirtualPath(string path)
 285        {
 89286            var appPaths = ApplicationPaths;
 287
 89288            return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
 89289                .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIg
 290        }
 291
 292        /// <summary>
 293        /// Creates the instance safe.
 294        /// </summary>
 295        /// <param name="type">The type.</param>
 296        /// <returns>System.Object.</returns>
 297        protected object CreateInstanceSafe(Type type)
 298        {
 4116299            _creatingInstances ??= new List<Type>();
 300
 4116301            if (_creatingInstances.Contains(type))
 302            {
 0303                Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
 0304                foreach (var entry in _creatingInstances)
 305                {
 0306                    Logger.LogError("Called from: {TypeName}", entry.FullName);
 307                }
 308
 0309                _pluginManager.FailPlugin(type.Assembly);
 310
 0311                throw new TypeLoadException("DI Loop detected");
 312            }
 313
 314            try
 315            {
 4116316                _creatingInstances.Add(type);
 4116317                Logger.LogDebug("Creating instance of {Type}", type);
 4116318                return ServiceProvider is null
 4116319                    ? Activator.CreateInstance(type)
 4116320                    : ActivatorUtilities.CreateInstance(ServiceProvider, type);
 321            }
 0322            catch (Exception ex)
 323            {
 0324                Logger.LogError(ex, "Error creating {Type}", type);
 325                // If this is a plugin fail it.
 0326                _pluginManager.FailPlugin(type.Assembly);
 0327                return null;
 328            }
 329            finally
 330            {
 4116331                _creatingInstances.Remove(type);
 4116332            }
 4116333        }
 334
 335        /// <summary>
 336        /// Resolves this instance.
 337        /// </summary>
 338        /// <typeparam name="T">The type.</typeparam>
 339        /// <returns>``0.</returns>
 462340        public T Resolve<T>() => ServiceProvider.GetService<T>();
 341
 342        /// <inheritdoc/>
 343        public IEnumerable<Type> GetExportTypes<T>()
 344        {
 345            var currentType = typeof(T);
 346            var numberOfConcreteTypes = _allConcreteTypes.Length;
 347            for (var i = 0; i < numberOfConcreteTypes; i++)
 348            {
 349                var type = _allConcreteTypes[i];
 350                if (currentType.IsAssignableFrom(type))
 351                {
 352                    yield return type;
 353                }
 354            }
 355        }
 356
 357        /// <inheritdoc />
 358        public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
 359        {
 360            // Convert to list so this isn't executed for each iteration
 294361            var parts = GetExportTypes<T>()
 294362                .Select(CreateInstanceSafe)
 294363                .Where(i => i is not null)
 294364                .Cast<T>()
 294365                .ToList();
 366
 294367            if (manageLifetime)
 368            {
 630369                foreach (var part in parts.OfType<IDisposable>())
 370                {
 42371                    _disposableParts.Add(part);
 372                }
 373            }
 374
 294375            return parts;
 376        }
 377
 378        /// <inheritdoc />
 379        public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
 380        {
 381            // Convert to list so this isn't executed for each iteration
 21382            var parts = GetExportTypes<T>()
 21383                .Select(i => defaultFunc(i))
 21384                .Where(i => i is not null)
 21385                .Cast<T>()
 21386                .ToList();
 387
 21388            if (manageLifetime)
 389            {
 42390                foreach (var part in parts.OfType<IDisposable>())
 391                {
 0392                    _disposableParts.Add(part);
 393                }
 394            }
 395
 21396            return parts;
 397        }
 398
 399        /// <summary>
 400        /// Runs the startup tasks.
 401        /// </summary>
 402        /// <returns><see cref="Task" />.</returns>
 403        public Task RunStartupTasksAsync()
 404        {
 21405            Logger.LogInformation("Running startup tasks");
 406
 21407            Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
 408
 21409            ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
 21410            ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
 411
 21412            var ffmpegValid = Resolve<IMediaEncoder>().SetFFmpegPath();
 413
 21414            if (!ffmpegValid)
 415            {
 0416                throw new FfmpegException("Failed to find valid ffmpeg");
 417            }
 418
 21419            Logger.LogInformation("ServerId: {ServerId}", SystemId);
 21420            Logger.LogInformation("Core startup complete");
 21421            CoreStartupHasCompleted = true;
 422
 21423            return Task.CompletedTask;
 424        }
 425
 426        /// <inheritdoc/>
 427        public void Init(IServiceCollection serviceCollection)
 428        {
 21429            DiscoverTypes();
 430
 21431            ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
 432
 21433            NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkMana
 434
 435            // Initialize runtime stat collection
 21436            if (ConfigurationManager.Configuration.EnableMetrics)
 437            {
 0438                _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
 439            }
 440
 21441            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 21442            HttpPort = networkConfiguration.InternalHttpPort;
 21443            HttpsPort = networkConfiguration.InternalHttpsPort;
 444
 445            // Safeguard against invalid configuration
 21446            if (HttpPort == HttpsPort)
 447            {
 0448                HttpPort = NetworkConfiguration.DefaultHttpPort;
 0449                HttpsPort = NetworkConfiguration.DefaultHttpsPort;
 450            }
 451
 21452            CertificatePath = networkConfiguration.CertificatePath;
 21453            Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
 454
 21455            RegisterServices(serviceCollection);
 456
 21457            _pluginManager.RegisterServices(serviceCollection);
 21458        }
 459
 460        /// <summary>
 461        /// Registers services/resources with the service collection that will be available via DI.
 462        /// </summary>
 463        /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
 464        protected virtual void RegisterServices(IServiceCollection serviceCollection)
 465        {
 21466            serviceCollection.AddSingleton(_startupOptions);
 467
 21468            serviceCollection.AddMemoryCache();
 469
 21470            serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
 21471            serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
 21472            serviceCollection.AddSingleton<IApplicationHost>(this);
 21473            serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
 21474            serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
 475
 21476            serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
 21477            serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
 478
 21479            serviceCollection.AddScoped<ISystemManager, SystemManager>();
 480
 21481            serviceCollection.AddSingleton<TmdbClientManager>();
 482
 21483            serviceCollection.AddSingleton(NetManager);
 484
 21485            serviceCollection.AddSingleton<ITaskManager, TaskManager>();
 486
 21487            serviceCollection.AddSingleton(_xmlSerializer);
 488
 21489            serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
 490
 21491            serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
 492
 21493            serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
 494
 21495            serviceCollection.AddSingleton<IServerApplicationHost>(this);
 21496            serviceCollection.AddSingleton(ApplicationPaths);
 497
 21498            serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
 499
 21500            serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
 501
 21502            serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
 503
 21504            serviceCollection.AddSingleton<IItemRepository, BaseItemRepository>();
 21505            serviceCollection.AddSingleton<IPeopleRepository, PeopleRepository>();
 21506            serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
 21507            serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
 21508            serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
 21509            serviceCollection.AddSingleton<IKeyframeRepository, KeyframeRepository>();
 21510            serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
 511
 21512            serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
 21513            serviceCollection.AddSingleton<EncodingHelper>();
 21514            serviceCollection.AddSingleton<IPathManager, PathManager>();
 21515            serviceCollection.AddSingleton<IExternalDataManager, ExternalDataManager>();
 516
 517            // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
 21518            serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMon
 21519            serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderM
 21520            serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewM
 21521            serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
 21522            serviceCollection.AddSingleton<NamingOptions>();
 523
 21524            serviceCollection.AddSingleton<IMusicManager, MusicManager>();
 525
 21526            serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
 527
 21528            serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
 529
 21530            serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
 531
 21532            serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
 533
 21534            serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
 535
 21536            serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
 537
 21538            serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
 21539            serviceCollection.AddSingleton<ILyricManager, LyricManager>();
 540
 21541            serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
 542
 543            // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
 21544            serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManag
 21545            serviceCollection.AddSingleton<IDtoService, DtoService>();
 546
 21547            serviceCollection.AddSingleton<ISessionManager, SessionManager>();
 548
 21549            serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
 550
 21551            serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
 552
 21553            serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
 554
 21555            serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
 556
 21557            serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
 558
 21559            serviceCollection.AddSingleton<IAuthService, AuthService>();
 21560            serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
 561
 21562            serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
 21563            serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
 21564            serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
 565
 21566            serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtrac
 567
 21568            serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
 21569            serviceCollection.AddScoped<MediaInfoHelper>();
 21570            serviceCollection.AddScoped<AudioHelper>();
 21571            serviceCollection.AddScoped<DynamicHlsHelper>();
 21572            serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
 21573            serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
 574
 21575            serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
 21576        }
 577
 578        /// <summary>
 579        /// Create services registered with the service container that need to be initialized at application startup.
 580        /// </summary>
 581        /// <param name="startupConfig">The configuration used to initialise the application.</param>
 582        /// <returns>A task representing the service initialization operation.</returns>
 583        public async Task InitializeServices(IConfiguration startupConfig)
 584        {
 585            var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
 586            await localizationManager.LoadAll().ConfigureAwait(false);
 587
 588            SetStaticProperties();
 589
 590            FindParts();
 591        }
 592
 593        private X509Certificate2 GetCertificate(string path, string password)
 594        {
 21595            if (string.IsNullOrWhiteSpace(path))
 596            {
 21597                return null;
 598            }
 599
 600            try
 601            {
 0602                if (!File.Exists(path))
 603                {
 0604                    return null;
 605                }
 606
 607                // Don't use an empty string password
 0608                password = string.IsNullOrWhiteSpace(password) ? null : password;
 609
 0610                var localCert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.UserKeySet)
 0611                if (!localCert.HasPrivateKey)
 612                {
 0613                    Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
 0614                    return null;
 615                }
 616
 0617                return localCert;
 618            }
 0619            catch (Exception ex)
 620            {
 0621                Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
 0622                return null;
 623            }
 0624        }
 625
 626        /// <summary>
 627        /// Dirty hacks.
 628        /// </summary>
 629        private void SetStaticProperties()
 630        {
 631            // For now there's no real way to inject these properly
 21632            BaseItem.ChapterManager = Resolve<IChapterManager>();
 21633            BaseItem.ChannelManager = Resolve<IChannelManager>();
 21634            BaseItem.ConfigurationManager = ConfigurationManager;
 21635            BaseItem.FileSystem = Resolve<IFileSystem>();
 21636            BaseItem.ItemRepository = Resolve<IItemRepository>();
 21637            BaseItem.LibraryManager = Resolve<ILibraryManager>();
 21638            BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
 21639            BaseItem.Logger = Resolve<ILogger<BaseItem>>();
 21640            BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
 21641            BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
 21642            BaseItem.ProviderManager = Resolve<IProviderManager>();
 21643            BaseItem.UserDataManager = Resolve<IUserDataManager>();
 21644            CollectionFolder.XmlSerializer = _xmlSerializer;
 21645            CollectionFolder.ApplicationHost = this;
 21646            Folder.UserViewManager = Resolve<IUserViewManager>();
 21647            Folder.CollectionManager = Resolve<ICollectionManager>();
 21648            Episode.MediaEncoder = Resolve<IMediaEncoder>();
 21649            UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
 21650            Video.RecordingsManager = Resolve<IRecordingsManager>();
 21651        }
 652
 653        /// <summary>
 654        /// Finds plugin components and register them with the appropriate services.
 655        /// </summary>
 656        private void FindParts()
 657        {
 21658            if (!ConfigurationManager.Configuration.IsPortAuthorized)
 659            {
 21660                ConfigurationManager.Configuration.IsPortAuthorized = true;
 21661                ConfigurationManager.SaveConfiguration();
 662            }
 663
 21664            _pluginManager.CreatePlugins();
 665
 21666            Resolve<ILibraryManager>().AddParts(
 21667                GetExports<IResolverIgnoreRule>(),
 21668                GetExports<IItemResolver>(),
 21669                GetExports<IIntroProvider>(),
 21670                GetExports<IBaseItemComparer>(),
 21671                GetExports<ILibraryPostScanTask>());
 672
 21673            Resolve<IProviderManager>().AddParts(
 21674                GetExports<IImageProvider>(),
 21675                GetExports<IMetadataService>(),
 21676                GetExports<IMetadataProvider>(),
 21677                GetExports<IMetadataSaver>(),
 21678                GetExports<IExternalId>(),
 21679                GetExports<IExternalUrlProvider>());
 680
 21681            Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
 21682        }
 683
 684        /// <summary>
 685        /// Discovers the types.
 686        /// </summary>
 687        protected void DiscoverTypes()
 688        {
 21689            Logger.LogInformation("Loading assemblies");
 690
 21691            _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
 21692        }
 693
 694        private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
 695        {
 696            foreach (var ass in assemblies)
 697            {
 698                Type[] exportedTypes;
 699                try
 700                {
 701                    exportedTypes = ass.GetExportedTypes();
 702                }
 703                catch (FileNotFoundException ex)
 704                {
 705                    Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
 706                    _pluginManager.FailPlugin(ass);
 707                    continue;
 708                }
 709                catch (TypeLoadException ex)
 710                {
 711                    Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
 712                    _pluginManager.FailPlugin(ass);
 713                    continue;
 714                }
 715
 716                foreach (Type type in exportedTypes)
 717                {
 718                    if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
 719                    {
 720                        yield return type;
 721                    }
 722                }
 723            }
 724        }
 725
 726        /// <summary>
 727        /// Called when [configuration updated].
 728        /// </summary>
 729        /// <param name="sender">The sender.</param>
 730        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 731        private void OnConfigurationUpdated(object sender, EventArgs e)
 732        {
 18733            var requiresRestart = false;
 18734            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 735
 736            // Don't do anything if these haven't been set yet
 18737            if (HttpPort != 0 && HttpsPort != 0)
 738            {
 739                // Need to restart if ports have changed
 18740                if (networkConfiguration.InternalHttpPort != HttpPort
 18741                    || networkConfiguration.InternalHttpsPort != HttpsPort)
 742                {
 0743                    if (ConfigurationManager.Configuration.IsPortAuthorized)
 744                    {
 0745                        ConfigurationManager.Configuration.IsPortAuthorized = false;
 0746                        ConfigurationManager.SaveConfiguration();
 747
 0748                        requiresRestart = true;
 749                    }
 750                }
 751            }
 752
 18753            if (ValidateSslCertificate(networkConfiguration))
 754            {
 0755                requiresRestart = true;
 756            }
 757
 18758            if (requiresRestart)
 759            {
 0760                Logger.LogInformation("App needs to be restarted due to configuration change.");
 761
 0762                NotifyPendingRestart();
 763            }
 18764        }
 765
 766        /// <summary>
 767        /// Validates the SSL certificate.
 768        /// </summary>
 769        /// <param name="networkConfig">The new configuration.</param>
 770        /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
 771        private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
 772        {
 18773            var newPath = networkConfig.CertificatePath;
 774
 18775            if (!string.IsNullOrWhiteSpace(newPath)
 18776                && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
 777            {
 0778                if (File.Exists(newPath))
 779                {
 0780                    return true;
 781                }
 782
 0783                throw new FileNotFoundException(
 0784                    string.Format(
 0785                        CultureInfo.InvariantCulture,
 0786                        "Certificate file '{0}' does not exist.",
 0787                        newPath));
 788            }
 789
 18790            return false;
 791        }
 792
 793        /// <summary>
 794        /// Notifies the kernel that a change has been made that requires a restart.
 795        /// </summary>
 796        public void NotifyPendingRestart()
 797        {
 0798            Logger.LogInformation("App needs to be restarted.");
 799
 0800            var changed = !HasPendingRestart;
 801
 0802            HasPendingRestart = true;
 803
 0804            if (changed)
 805            {
 0806                EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
 807            }
 0808        }
 809
 810        /// <summary>
 811        /// Gets the composable part assemblies.
 812        /// </summary>
 813        /// <returns>IEnumerable{Assembly}.</returns>
 814        protected IEnumerable<Assembly> GetComposablePartAssemblies()
 815        {
 816            foreach (var p in _pluginManager.LoadAssemblies())
 817            {
 818                yield return p;
 819            }
 820
 821            // Include composable parts in the Model assembly
 822            yield return typeof(SystemInfo).Assembly;
 823
 824            // Include composable parts in the Common assembly
 825            yield return typeof(IApplicationHost).Assembly;
 826
 827            // Include composable parts in the Controller assembly
 828            yield return typeof(IServerApplicationHost).Assembly;
 829
 830            // Include composable parts in the Providers assembly
 831            yield return typeof(ProviderManager).Assembly;
 832
 833            // Include composable parts in the Photos assembly
 834            yield return typeof(PhotoProvider).Assembly;
 835
 836            // Emby.Server implementations
 837            yield return typeof(InstallationManager).Assembly;
 838
 839            // MediaEncoding
 840            yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
 841
 842            // Local metadata
 843            yield return typeof(BoxSetXmlSaver).Assembly;
 844
 845            // Xbmc
 846            yield return typeof(ArtistNfoProvider).Assembly;
 847
 848            // Network
 849            yield return typeof(NetworkManager).Assembly;
 850
 851            // Hls
 852            yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
 853
 854            foreach (var i in GetAssembliesWithPartsInternal())
 855            {
 856                yield return i;
 857            }
 858        }
 859
 860        protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
 861
 862        /// <inheritdoc/>
 863        public string GetSmartApiUrl(IPAddress remoteAddr)
 864        {
 865            // Published server ends with a /
 0866            if (!string.IsNullOrEmpty(PublishedServerUrl))
 867            {
 868                // Published server ends with a '/', so we need to remove it.
 0869                return PublishedServerUrl.Trim('/');
 870            }
 871
 0872            string smart = NetManager.GetBindAddress(remoteAddr, out var port);
 0873            return GetLocalApiUrl(smart.Trim('/'), null, port);
 874        }
 875
 876        /// <inheritdoc/>
 877        public string GetSmartApiUrl(HttpRequest request)
 878        {
 879            // Return the host in the HTTP request as the API URL if not configured otherwise
 0880            if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
 881            {
 0882                int? requestPort = request.Host.Port;
 0883                if (requestPort is null
 0884                    || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
 0885                    || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)
 886                {
 0887                    requestPort = -1;
 888                }
 889
 0890                return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
 891            }
 892
 0893            return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
 894        }
 895
 896        /// <inheritdoc/>
 897        public string GetSmartApiUrl(string hostname)
 898        {
 899            // Published server ends with a /
 0900            if (!string.IsNullOrEmpty(PublishedServerUrl))
 901            {
 902                // Published server ends with a '/', so we need to remove it.
 0903                return PublishedServerUrl.Trim('/');
 904            }
 905
 0906            string smart = NetManager.GetBindAddress(hostname, out var port);
 0907            return GetLocalApiUrl(smart.Trim('/'), null, port);
 908        }
 909
 910        /// <inheritdoc/>
 911        public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
 912        {
 913            // With an empty source, the port will be null
 0914            var smart = NetManager.GetBindAddress(ipAddress, out _, false);
 0915            var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
 0916            int? port = !allowHttps ? HttpPort : null;
 0917            return GetLocalApiUrl(smart, scheme, port);
 918        }
 919
 920        /// <inheritdoc/>
 921        public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
 922        {
 923            // If the smartAPI doesn't start with http then treat it as a host or ip.
 0924            if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
 925            {
 0926                return hostname.TrimEnd('/');
 927            }
 928
 929            // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
 930            // not. For consistency, always trim the trailing slash.
 0931            scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 0932            var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
 0933            return new UriBuilder
 0934            {
 0935                Scheme = scheme,
 0936                Host = hostname,
 0937                Port = port ?? (isHttps ? HttpsPort : HttpPort),
 0938                Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
 0939            }.ToString().TrimEnd('/');
 940        }
 941
 942        public IEnumerable<Assembly> GetApiPluginAssemblies()
 943        {
 944            var assemblies = _allConcreteTypes
 945                .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
 946                .Select(i => i.Assembly)
 947                .Distinct();
 948
 949            foreach (var assembly in assemblies)
 950            {
 951                Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
 952                yield return assembly;
 953            }
 954        }
 955
 956        /// <inheritdoc />
 957        public void Dispose()
 958        {
 21959            Dispose(true);
 21960            GC.SuppressFinalize(this);
 21961        }
 962
 963        /// <summary>
 964        /// Releases unmanaged and - optionally - managed resources.
 965        /// </summary>
 966        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 967        protected virtual void Dispose(bool dispose)
 968        {
 21969            if (_disposed)
 970            {
 0971                return;
 972            }
 973
 21974            if (dispose)
 975            {
 21976                var type = GetType();
 977
 21978                Logger.LogInformation("Disposing {Type}", type.Name);
 979
 168980                foreach (var part in _disposableParts.ToArray())
 981                {
 63982                    var partType = part.GetType();
 63983                    if (partType == type)
 984                    {
 985                        continue;
 986                    }
 987
 63988                    Logger.LogInformation("Disposing {Type}", partType.Name);
 989
 990                    try
 991                    {
 63992                        part.Dispose();
 63993                    }
 0994                    catch (Exception ex)
 995                    {
 0996                        Logger.LogError(ex, "Error disposing {Type}", partType.Name);
 0997                    }
 998                }
 999
 211000                _disposableParts.Clear();
 1001            }
 1002
 211003            _disposed = true;
 211004        }
 1005    }
 1006}