< 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: 223
Uncovered lines: 87
Coverable lines: 310
Total lines: 1011
Line coverage: 71.9%
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.LiveTv;
 66using MediaBrowser.Controller.Lyrics;
 67using MediaBrowser.Controller.MediaEncoding;
 68using MediaBrowser.Controller.MediaSegments;
 69using MediaBrowser.Controller.Net;
 70using MediaBrowser.Controller.Persistence;
 71using MediaBrowser.Controller.Playlists;
 72using MediaBrowser.Controller.Providers;
 73using MediaBrowser.Controller.QuickConnect;
 74using MediaBrowser.Controller.Resolvers;
 75using MediaBrowser.Controller.Session;
 76using MediaBrowser.Controller.Sorting;
 77using MediaBrowser.Controller.Subtitles;
 78using MediaBrowser.Controller.SyncPlay;
 79using MediaBrowser.Controller.TV;
 80using MediaBrowser.LocalMetadata.Savers;
 81using MediaBrowser.MediaEncoding.BdInfo;
 82using MediaBrowser.MediaEncoding.Subtitles;
 83using MediaBrowser.MediaEncoding.Transcoding;
 84using MediaBrowser.Model.Cryptography;
 85using MediaBrowser.Model.Globalization;
 86using MediaBrowser.Model.IO;
 87using MediaBrowser.Model.MediaInfo;
 88using MediaBrowser.Model.Net;
 89using MediaBrowser.Model.Serialization;
 90using MediaBrowser.Model.System;
 91using MediaBrowser.Model.Tasks;
 92using MediaBrowser.Providers.Lyric;
 93using MediaBrowser.Providers.Manager;
 94using MediaBrowser.Providers.Plugins.Tmdb;
 95using MediaBrowser.Providers.Subtitles;
 96using MediaBrowser.XbmcMetadata.Providers;
 97using Microsoft.AspNetCore.Http;
 98using Microsoft.AspNetCore.Mvc;
 99using Microsoft.Extensions.Configuration;
 100using Microsoft.Extensions.DependencyInjection;
 101using Microsoft.Extensions.Logging;
 102using Prometheus.DotNetRuntime;
 103using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 104using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
 105using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
 106
 107namespace Emby.Server.Implementations
 108{
 109    /// <summary>
 110    /// Class CompositionRoot.
 111    /// </summary>
 112    public abstract class ApplicationHost : IServerApplicationHost, IDisposable
 113    {
 114        /// <summary>
 115        /// The disposable parts.
 116        /// </summary>
 21117        private readonly ConcurrentBag<IDisposable> _disposableParts = new();
 118        private readonly DeviceId _deviceId;
 119
 120        private readonly IConfiguration _startupConfig;
 121        private readonly IXmlSerializer _xmlSerializer;
 122        private readonly IStartupOptions _startupOptions;
 123        private readonly PluginManager _pluginManager;
 124
 125        private List<Type> _creatingInstances;
 126
 127        /// <summary>
 128        /// Gets or sets all concrete types.
 129        /// </summary>
 130        /// <value>All concrete types.</value>
 131        private Type[] _allConcreteTypes;
 132
 133        private bool _disposed;
 134
 135        /// <summary>
 136        /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
 137        /// </summary>
 138        /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
 139        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
 140        /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
 141        /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
 142        protected ApplicationHost(
 143            IServerApplicationPaths applicationPaths,
 144            ILoggerFactory loggerFactory,
 145            IStartupOptions options,
 146            IConfiguration startupConfig)
 147        {
 148            ApplicationPaths = applicationPaths;
 149            LoggerFactory = loggerFactory;
 21150            _startupOptions = options;
 21151            _startupConfig = startupConfig;
 152
 21153            Logger = LoggerFactory.CreateLogger<ApplicationHost>();
 21154            _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
 155
 21156            ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
 21157            ApplicationVersionString = ApplicationVersion.ToString(3);
 21158            ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
 159
 21160            _xmlSerializer = new MyXmlSerializer();
 21161            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
 21162            _pluginManager = new PluginManager(
 21163                LoggerFactory.CreateLogger<PluginManager>(),
 21164                this,
 21165                ConfigurationManager.Configuration,
 21166                ApplicationPaths.PluginsPath,
 21167                ApplicationVersion);
 168
 21169            _disposableParts.Add(_pluginManager);
 21170        }
 171
 172        /// <summary>
 173        /// Occurs when [has pending restart changed].
 174        /// </summary>
 175        public event EventHandler HasPendingRestartChanged;
 176
 177        /// <summary>
 178        /// Gets the value of the PublishedServerUrl setting.
 179        /// </summary>
 0180        private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
 181
 182        public bool CoreStartupHasCompleted { get; private set; }
 183
 184        /// <summary>
 185        /// Gets the <see cref="INetworkManager"/> singleton instance.
 186        /// </summary>
 187        public INetworkManager NetManager { get; private set; }
 188
 189        /// <inheritdoc />
 190        public bool HasPendingRestart { get; private set; }
 191
 192        /// <inheritdoc />
 193        public bool ShouldRestart { get; set; }
 194
 195        /// <summary>
 196        /// Gets the logger.
 197        /// </summary>
 198        protected ILogger<ApplicationHost> Logger { get; }
 199
 200        /// <summary>
 201        /// Gets the logger factory.
 202        /// </summary>
 203        protected ILoggerFactory LoggerFactory { get; }
 204
 205        /// <summary>
 206        /// Gets the application paths.
 207        /// </summary>
 208        /// <value>The application paths.</value>
 209        protected IServerApplicationPaths ApplicationPaths { get; }
 210
 211        /// <summary>
 212        /// Gets the configuration manager.
 213        /// </summary>
 214        /// <value>The configuration manager.</value>
 215        public ServerConfigurationManager ConfigurationManager { get; }
 216
 217        /// <summary>
 218        /// Gets or sets the service provider.
 219        /// </summary>
 220        public IServiceProvider ServiceProvider { get; set; }
 221
 222        /// <summary>
 223        /// Gets the http port for the webhost.
 224        /// </summary>
 225        public int HttpPort { get; private set; }
 226
 227        /// <summary>
 228        /// Gets the https port for the webhost.
 229        /// </summary>
 230        public int HttpsPort { get; private set; }
 231
 232        /// <inheritdoc />
 233        public Version ApplicationVersion { get; }
 234
 235        /// <inheritdoc />
 236        public string ApplicationVersionString { get; }
 237
 238        /// <summary>
 239        /// Gets the current application user agent.
 240        /// </summary>
 241        /// <value>The application user agent.</value>
 242        public string ApplicationUserAgent { get; }
 243
 244        /// <summary>
 245        /// Gets the email address for use within a comment section of a user agent field.
 246        /// Presently used to provide contact information to MusicBrainz service.
 247        /// </summary>
 21248        public string ApplicationUserAgentAddress => "team@jellyfin.org";
 249
 250        /// <summary>
 251        /// Gets the current application name.
 252        /// </summary>
 253        /// <value>The application name.</value>
 21254        public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Locat
 255
 98256        public string SystemId => _deviceId.Value;
 257
 258        /// <inheritdoc/>
 63259        public string Name => ApplicationProductName;
 260
 261        private string CertificatePath { get; set; }
 262
 263        public X509Certificate2 Certificate { get; private set; }
 264
 265        /// <inheritdoc/>
 0266        public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableH
 267
 268        public string FriendlyName =>
 0269            string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
 0270                ? Environment.MachineName
 0271                : ConfigurationManager.Configuration.ServerName;
 272
 273        public string RestoreBackupPath { get; set; }
 274
 275        public string ExpandVirtualPath(string path)
 276        {
 84277            if (path is null)
 278            {
 0279                return null;
 280            }
 281
 84282            var appPaths = ApplicationPaths;
 283
 84284            return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
 84285                .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIg
 286        }
 287
 288        public string ReverseVirtualPath(string path)
 289        {
 93290            var appPaths = ApplicationPaths;
 291
 93292            return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
 93293                .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIg
 294        }
 295
 296        /// <summary>
 297        /// Creates the instance safe.
 298        /// </summary>
 299        /// <param name="type">The type.</param>
 300        /// <returns>System.Object.</returns>
 301        protected object CreateInstanceSafe(Type type)
 302        {
 4116303            _creatingInstances ??= new List<Type>();
 304
 4116305            if (_creatingInstances.Contains(type))
 306            {
 0307                Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
 0308                foreach (var entry in _creatingInstances)
 309                {
 0310                    Logger.LogError("Called from: {TypeName}", entry.FullName);
 311                }
 312
 0313                _pluginManager.FailPlugin(type.Assembly);
 314
 0315                throw new TypeLoadException("DI Loop detected");
 316            }
 317
 318            try
 319            {
 4116320                _creatingInstances.Add(type);
 4116321                Logger.LogDebug("Creating instance of {Type}", type);
 4116322                return ServiceProvider is null
 4116323                    ? Activator.CreateInstance(type)
 4116324                    : ActivatorUtilities.CreateInstance(ServiceProvider, type);
 325            }
 0326            catch (Exception ex)
 327            {
 0328                Logger.LogError(ex, "Error creating {Type}", type);
 329                // If this is a plugin fail it.
 0330                _pluginManager.FailPlugin(type.Assembly);
 0331                return null;
 332            }
 333            finally
 334            {
 4116335                _creatingInstances.Remove(type);
 4116336            }
 4116337        }
 338
 339        /// <summary>
 340        /// Resolves this instance.
 341        /// </summary>
 342        /// <typeparam name="T">The type.</typeparam>
 343        /// <returns>``0.</returns>
 462344        public T Resolve<T>() => ServiceProvider.GetService<T>();
 345
 346        /// <inheritdoc/>
 347        public IEnumerable<Type> GetExportTypes<T>()
 348        {
 349            var currentType = typeof(T);
 350            var numberOfConcreteTypes = _allConcreteTypes.Length;
 351            for (var i = 0; i < numberOfConcreteTypes; i++)
 352            {
 353                var type = _allConcreteTypes[i];
 354                if (currentType.IsAssignableFrom(type))
 355                {
 356                    yield return type;
 357                }
 358            }
 359        }
 360
 361        /// <inheritdoc />
 362        public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
 363        {
 364            // Convert to list so this isn't executed for each iteration
 294365            var parts = GetExportTypes<T>()
 294366                .Select(CreateInstanceSafe)
 294367                .Where(i => i is not null)
 294368                .Cast<T>()
 294369                .ToList();
 370
 294371            if (manageLifetime)
 372            {
 630373                foreach (var part in parts.OfType<IDisposable>())
 374                {
 42375                    _disposableParts.Add(part);
 376                }
 377            }
 378
 294379            return parts;
 380        }
 381
 382        /// <inheritdoc />
 383        public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
 384        {
 385            // Convert to list so this isn't executed for each iteration
 21386            var parts = GetExportTypes<T>()
 21387                .Select(i => defaultFunc(i))
 21388                .Where(i => i is not null)
 21389                .Cast<T>()
 21390                .ToList();
 391
 21392            if (manageLifetime)
 393            {
 42394                foreach (var part in parts.OfType<IDisposable>())
 395                {
 0396                    _disposableParts.Add(part);
 397                }
 398            }
 399
 21400            return parts;
 401        }
 402
 403        /// <summary>
 404        /// Runs the startup tasks.
 405        /// </summary>
 406        /// <returns><see cref="Task" />.</returns>
 407        public Task RunStartupTasksAsync()
 408        {
 21409            Logger.LogInformation("Running startup tasks");
 410
 21411            Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
 412
 21413            ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
 21414            ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
 415
 21416            var ffmpegValid = Resolve<IMediaEncoder>().SetFFmpegPath();
 417
 21418            if (!ffmpegValid)
 419            {
 0420                throw new FfmpegException("Failed to find valid ffmpeg");
 421            }
 422
 21423            Logger.LogInformation("ServerId: {ServerId}", SystemId);
 21424            Logger.LogInformation("Core startup complete");
 21425            CoreStartupHasCompleted = true;
 426
 21427            return Task.CompletedTask;
 428        }
 429
 430        /// <inheritdoc/>
 431        public void Init(IServiceCollection serviceCollection)
 432        {
 21433            DiscoverTypes();
 434
 21435            ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
 436
 21437            NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkMana
 438
 439            // Initialize runtime stat collection
 21440            if (ConfigurationManager.Configuration.EnableMetrics)
 441            {
 0442                _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
 443            }
 444
 21445            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 21446            HttpPort = networkConfiguration.InternalHttpPort;
 21447            HttpsPort = networkConfiguration.InternalHttpsPort;
 448
 449            // Safeguard against invalid configuration
 21450            if (HttpPort == HttpsPort)
 451            {
 0452                HttpPort = NetworkConfiguration.DefaultHttpPort;
 0453                HttpsPort = NetworkConfiguration.DefaultHttpsPort;
 454            }
 455
 21456            CertificatePath = networkConfiguration.CertificatePath;
 21457            Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
 458
 21459            RegisterServices(serviceCollection);
 460
 21461            _pluginManager.RegisterServices(serviceCollection);
 21462        }
 463
 464        /// <summary>
 465        /// Registers services/resources with the service collection that will be available via DI.
 466        /// </summary>
 467        /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
 468        protected virtual void RegisterServices(IServiceCollection serviceCollection)
 469        {
 21470            serviceCollection.AddSingleton(_startupOptions);
 471
 21472            serviceCollection.AddMemoryCache();
 473
 21474            serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
 21475            serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
 21476            serviceCollection.AddSingleton<IApplicationHost>(this);
 21477            serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
 21478            serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
 21479            serviceCollection.AddSingleton<IBackupService, BackupService>();
 480
 21481            serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
 21482            serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
 483
 21484            serviceCollection.AddScoped<ISystemManager, SystemManager>();
 485
 21486            serviceCollection.AddSingleton<TmdbClientManager>();
 487
 21488            serviceCollection.AddSingleton(NetManager);
 489
 21490            serviceCollection.AddSingleton<ITaskManager, TaskManager>();
 491
 21492            serviceCollection.AddSingleton(_xmlSerializer);
 493
 21494            serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
 495
 21496            serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
 497
 21498            serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
 499
 21500            serviceCollection.AddSingleton<IServerApplicationHost>(this);
 21501            serviceCollection.AddSingleton(ApplicationPaths);
 502
 21503            serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
 504
 21505            serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
 506
 21507            serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
 508
 21509            serviceCollection.AddSingleton<IItemRepository, BaseItemRepository>();
 21510            serviceCollection.AddSingleton<IPeopleRepository, PeopleRepository>();
 21511            serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
 21512            serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
 21513            serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
 21514            serviceCollection.AddSingleton<IKeyframeRepository, KeyframeRepository>();
 21515            serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
 516
 21517            serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
 21518            serviceCollection.AddSingleton<EncodingHelper>();
 21519            serviceCollection.AddSingleton<IPathManager, PathManager>();
 21520            serviceCollection.AddSingleton<IExternalDataManager, ExternalDataManager>();
 521
 522            // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
 21523            serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMon
 21524            serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderM
 21525            serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewM
 21526            serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
 21527            serviceCollection.AddSingleton<NamingOptions>();
 528
 21529            serviceCollection.AddSingleton<IMusicManager, MusicManager>();
 530
 21531            serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
 532
 21533            serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
 534
 21535            serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
 536
 21537            serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
 538
 21539            serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
 540
 21541            serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
 542
 21543            serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
 21544            serviceCollection.AddSingleton<ILyricManager, LyricManager>();
 545
 21546            serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
 547
 548            // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
 21549            serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManag
 21550            serviceCollection.AddSingleton<IDtoService, DtoService>();
 551
 21552            serviceCollection.AddSingleton<ISessionManager, SessionManager>();
 553
 21554            serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
 555
 21556            serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
 557
 21558            serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
 559
 21560            serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
 561
 21562            serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
 563
 21564            serviceCollection.AddSingleton<IAuthService, AuthService>();
 21565            serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
 566
 21567            serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
 21568            serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
 21569            serviceCollection.AddSingleton<IKeyframeManager, KeyframeManager>();
 570
 21571            serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtrac
 572
 21573            serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
 21574            serviceCollection.AddScoped<MediaInfoHelper>();
 21575            serviceCollection.AddScoped<AudioHelper>();
 21576            serviceCollection.AddScoped<DynamicHlsHelper>();
 21577            serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
 21578            serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
 579
 21580            serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
 21581        }
 582
 583        /// <summary>
 584        /// Create services registered with the service container that need to be initialized at application startup.
 585        /// </summary>
 586        /// <param name="startupConfig">The configuration used to initialise the application.</param>
 587        /// <returns>A task representing the service initialization operation.</returns>
 588        public async Task InitializeServices(IConfiguration startupConfig)
 589        {
 590            var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
 591            await localizationManager.LoadAll().ConfigureAwait(false);
 592
 593            SetStaticProperties();
 594
 595            FindParts();
 596        }
 597
 598        private X509Certificate2 GetCertificate(string path, string password)
 599        {
 21600            if (string.IsNullOrWhiteSpace(path))
 601            {
 21602                return null;
 603            }
 604
 605            try
 606            {
 0607                if (!File.Exists(path))
 608                {
 0609                    return null;
 610                }
 611
 612                // Don't use an empty string password
 0613                password = string.IsNullOrWhiteSpace(password) ? null : password;
 614
 0615                var localCert = X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.UserKeySet)
 0616                if (!localCert.HasPrivateKey)
 617                {
 0618                    Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
 0619                    return null;
 620                }
 621
 0622                return localCert;
 623            }
 0624            catch (Exception ex)
 625            {
 0626                Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
 0627                return null;
 628            }
 0629        }
 630
 631        /// <summary>
 632        /// Dirty hacks.
 633        /// </summary>
 634        private void SetStaticProperties()
 635        {
 636            // For now there's no real way to inject these properly
 21637            BaseItem.ChapterManager = Resolve<IChapterManager>();
 21638            BaseItem.ChannelManager = Resolve<IChannelManager>();
 21639            BaseItem.ConfigurationManager = ConfigurationManager;
 21640            BaseItem.FileSystem = Resolve<IFileSystem>();
 21641            BaseItem.ItemRepository = Resolve<IItemRepository>();
 21642            BaseItem.LibraryManager = Resolve<ILibraryManager>();
 21643            BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
 21644            BaseItem.Logger = Resolve<ILogger<BaseItem>>();
 21645            BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
 21646            BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
 21647            BaseItem.ProviderManager = Resolve<IProviderManager>();
 21648            BaseItem.UserDataManager = Resolve<IUserDataManager>();
 21649            CollectionFolder.XmlSerializer = _xmlSerializer;
 21650            CollectionFolder.ApplicationHost = this;
 21651            Folder.UserViewManager = Resolve<IUserViewManager>();
 21652            Folder.CollectionManager = Resolve<ICollectionManager>();
 21653            Episode.MediaEncoder = Resolve<IMediaEncoder>();
 21654            UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
 21655            Video.RecordingsManager = Resolve<IRecordingsManager>();
 21656        }
 657
 658        /// <summary>
 659        /// Finds plugin components and register them with the appropriate services.
 660        /// </summary>
 661        private void FindParts()
 662        {
 21663            if (!ConfigurationManager.Configuration.IsPortAuthorized)
 664            {
 21665                ConfigurationManager.Configuration.IsPortAuthorized = true;
 21666                ConfigurationManager.SaveConfiguration();
 667            }
 668
 21669            _pluginManager.CreatePlugins();
 670
 21671            Resolve<ILibraryManager>().AddParts(
 21672                GetExports<IResolverIgnoreRule>(),
 21673                GetExports<IItemResolver>(),
 21674                GetExports<IIntroProvider>(),
 21675                GetExports<IBaseItemComparer>(),
 21676                GetExports<ILibraryPostScanTask>());
 677
 21678            Resolve<IProviderManager>().AddParts(
 21679                GetExports<IImageProvider>(),
 21680                GetExports<IMetadataService>(),
 21681                GetExports<IMetadataProvider>(),
 21682                GetExports<IMetadataSaver>(),
 21683                GetExports<IExternalId>(),
 21684                GetExports<IExternalUrlProvider>());
 685
 21686            Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
 21687        }
 688
 689        /// <summary>
 690        /// Discovers the types.
 691        /// </summary>
 692        protected void DiscoverTypes()
 693        {
 21694            Logger.LogInformation("Loading assemblies");
 695
 21696            _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
 21697        }
 698
 699        private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
 700        {
 701            foreach (var ass in assemblies)
 702            {
 703                Type[] exportedTypes;
 704                try
 705                {
 706                    exportedTypes = ass.GetExportedTypes();
 707                }
 708                catch (FileNotFoundException ex)
 709                {
 710                    Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
 711                    _pluginManager.FailPlugin(ass);
 712                    continue;
 713                }
 714                catch (TypeLoadException ex)
 715                {
 716                    Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
 717                    _pluginManager.FailPlugin(ass);
 718                    continue;
 719                }
 720
 721                foreach (Type type in exportedTypes)
 722                {
 723                    if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
 724                    {
 725                        yield return type;
 726                    }
 727                }
 728            }
 729        }
 730
 731        /// <summary>
 732        /// Called when [configuration updated].
 733        /// </summary>
 734        /// <param name="sender">The sender.</param>
 735        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 736        private void OnConfigurationUpdated(object sender, EventArgs e)
 737        {
 18738            var requiresRestart = false;
 18739            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 740
 741            // Don't do anything if these haven't been set yet
 18742            if (HttpPort != 0 && HttpsPort != 0)
 743            {
 744                // Need to restart if ports have changed
 18745                if (networkConfiguration.InternalHttpPort != HttpPort
 18746                    || networkConfiguration.InternalHttpsPort != HttpsPort)
 747                {
 0748                    if (ConfigurationManager.Configuration.IsPortAuthorized)
 749                    {
 0750                        ConfigurationManager.Configuration.IsPortAuthorized = false;
 0751                        ConfigurationManager.SaveConfiguration();
 752
 0753                        requiresRestart = true;
 754                    }
 755                }
 756            }
 757
 18758            if (ValidateSslCertificate(networkConfiguration))
 759            {
 0760                requiresRestart = true;
 761            }
 762
 18763            if (requiresRestart)
 764            {
 0765                Logger.LogInformation("App needs to be restarted due to configuration change.");
 766
 0767                NotifyPendingRestart();
 768            }
 18769        }
 770
 771        /// <summary>
 772        /// Validates the SSL certificate.
 773        /// </summary>
 774        /// <param name="networkConfig">The new configuration.</param>
 775        /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
 776        private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
 777        {
 18778            var newPath = networkConfig.CertificatePath;
 779
 18780            if (!string.IsNullOrWhiteSpace(newPath)
 18781                && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
 782            {
 0783                if (File.Exists(newPath))
 784                {
 0785                    return true;
 786                }
 787
 0788                throw new FileNotFoundException(
 0789                    string.Format(
 0790                        CultureInfo.InvariantCulture,
 0791                        "Certificate file '{0}' does not exist.",
 0792                        newPath));
 793            }
 794
 18795            return false;
 796        }
 797
 798        /// <summary>
 799        /// Notifies the kernel that a change has been made that requires a restart.
 800        /// </summary>
 801        public void NotifyPendingRestart()
 802        {
 0803            Logger.LogInformation("App needs to be restarted.");
 804
 0805            var changed = !HasPendingRestart;
 806
 0807            HasPendingRestart = true;
 808
 0809            if (changed)
 810            {
 0811                EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
 812            }
 0813        }
 814
 815        /// <summary>
 816        /// Gets the composable part assemblies.
 817        /// </summary>
 818        /// <returns>IEnumerable{Assembly}.</returns>
 819        protected IEnumerable<Assembly> GetComposablePartAssemblies()
 820        {
 821            foreach (var p in _pluginManager.LoadAssemblies())
 822            {
 823                yield return p;
 824            }
 825
 826            // Include composable parts in the Model assembly
 827            yield return typeof(SystemInfo).Assembly;
 828
 829            // Include composable parts in the Common assembly
 830            yield return typeof(IApplicationHost).Assembly;
 831
 832            // Include composable parts in the Controller assembly
 833            yield return typeof(IServerApplicationHost).Assembly;
 834
 835            // Include composable parts in the Providers assembly
 836            yield return typeof(ProviderManager).Assembly;
 837
 838            // Include composable parts in the Photos assembly
 839            yield return typeof(PhotoProvider).Assembly;
 840
 841            // Emby.Server implementations
 842            yield return typeof(InstallationManager).Assembly;
 843
 844            // MediaEncoding
 845            yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
 846
 847            // Local metadata
 848            yield return typeof(BoxSetXmlSaver).Assembly;
 849
 850            // Xbmc
 851            yield return typeof(ArtistNfoProvider).Assembly;
 852
 853            // Network
 854            yield return typeof(NetworkManager).Assembly;
 855
 856            // Hls
 857            yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
 858
 859            foreach (var i in GetAssembliesWithPartsInternal())
 860            {
 861                yield return i;
 862            }
 863        }
 864
 865        protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
 866
 867        /// <inheritdoc/>
 868        public string GetSmartApiUrl(IPAddress remoteAddr)
 869        {
 870            // Published server ends with a /
 0871            if (!string.IsNullOrEmpty(PublishedServerUrl))
 872            {
 873                // Published server ends with a '/', so we need to remove it.
 0874                return PublishedServerUrl.Trim('/');
 875            }
 876
 0877            string smart = NetManager.GetBindAddress(remoteAddr, out var port);
 0878            return GetLocalApiUrl(smart.Trim('/'), null, port);
 879        }
 880
 881        /// <inheritdoc/>
 882        public string GetSmartApiUrl(HttpRequest request)
 883        {
 884            // Return the host in the HTTP request as the API URL if not configured otherwise
 0885            if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
 886            {
 0887                int? requestPort = request.Host.Port;
 0888                if (requestPort is null
 0889                    || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
 0890                    || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)
 891                {
 0892                    requestPort = -1;
 893                }
 894
 0895                return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
 896            }
 897
 0898            return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
 899        }
 900
 901        /// <inheritdoc/>
 902        public string GetSmartApiUrl(string hostname)
 903        {
 904            // Published server ends with a /
 0905            if (!string.IsNullOrEmpty(PublishedServerUrl))
 906            {
 907                // Published server ends with a '/', so we need to remove it.
 0908                return PublishedServerUrl.Trim('/');
 909            }
 910
 0911            string smart = NetManager.GetBindAddress(hostname, out var port);
 0912            return GetLocalApiUrl(smart.Trim('/'), null, port);
 913        }
 914
 915        /// <inheritdoc/>
 916        public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
 917        {
 918            // With an empty source, the port will be null
 0919            var smart = NetManager.GetBindAddress(ipAddress, out _, false);
 0920            var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
 0921            int? port = !allowHttps ? HttpPort : null;
 0922            return GetLocalApiUrl(smart, scheme, port);
 923        }
 924
 925        /// <inheritdoc/>
 926        public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
 927        {
 928            // If the smartAPI doesn't start with http then treat it as a host or ip.
 0929            if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
 930            {
 0931                return hostname.TrimEnd('/');
 932            }
 933
 934            // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
 935            // not. For consistency, always trim the trailing slash.
 0936            scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 0937            var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
 0938            return new UriBuilder
 0939            {
 0940                Scheme = scheme,
 0941                Host = hostname,
 0942                Port = port ?? (isHttps ? HttpsPort : HttpPort),
 0943                Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
 0944            }.ToString().TrimEnd('/');
 945        }
 946
 947        public IEnumerable<Assembly> GetApiPluginAssemblies()
 948        {
 949            var assemblies = _allConcreteTypes
 950                .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
 951                .Select(i => i.Assembly)
 952                .Distinct();
 953
 954            foreach (var assembly in assemblies)
 955            {
 956                Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
 957                yield return assembly;
 958            }
 959        }
 960
 961        /// <inheritdoc />
 962        public void Dispose()
 963        {
 21964            Dispose(true);
 21965            GC.SuppressFinalize(this);
 21966        }
 967
 968        /// <summary>
 969        /// Releases unmanaged and - optionally - managed resources.
 970        /// </summary>
 971        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 972        protected virtual void Dispose(bool dispose)
 973        {
 21974            if (_disposed)
 975            {
 0976                return;
 977            }
 978
 21979            if (dispose)
 980            {
 21981                var type = GetType();
 982
 21983                Logger.LogInformation("Disposing {Type}", type.Name);
 984
 168985                foreach (var part in _disposableParts.ToArray())
 986                {
 63987                    var partType = part.GetType();
 63988                    if (partType == type)
 989                    {
 990                        continue;
 991                    }
 992
 63993                    Logger.LogInformation("Disposing {Type}", partType.Name);
 994
 995                    try
 996                    {
 63997                        part.Dispose();
 63998                    }
 0999                    catch (Exception ex)
 1000                    {
 01001                        Logger.LogError(ex, "Error disposing {Type}", partType.Name);
 01002                    }
 1003                }
 1004
 211005                _disposableParts.Clear();
 1006            }
 1007
 211008            _disposed = true;
 211009        }
 1010    }
 1011}