< 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: 213
Uncovered lines: 85
Coverable lines: 298
Total lines: 1004
Line coverage: 71.4%
Branch coverage
40%
Covered branches: 41
Total branches: 102
Branch coverage: 40.1%
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()50%22100%
get_FriendlyName()0%620%
ExpandVirtualPath(...)100%11100%
ReverseVirtualPath(...)100%11100%
CreateInstanceSafe(...)62.5%14.8852.63%
Resolve()100%11100%
GetExports(...)100%66100%
GetExports(...)83.33%6.05688.88%
RunStartupTasksAsync()50%2290.9%
Init(...)50%4.11481.25%
RegisterServices(...)100%11100%
GetCertificate(...)12.5%48.31814.28%
SetStaticProperties()100%11100%
FindParts()100%22100%
DiscoverTypes()100%11100%
OnConfigurationUpdated(...)64.28%33.921453.33%
ValidateSslCertificate(...)33.33%15.28636.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%8.83876.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.Collections;
 19using Emby.Server.Implementations.Configuration;
 20using Emby.Server.Implementations.Cryptography;
 21using Emby.Server.Implementations.Data;
 22using Emby.Server.Implementations.Devices;
 23using Emby.Server.Implementations.Dto;
 24using Emby.Server.Implementations.HttpServer.Security;
 25using Emby.Server.Implementations.IO;
 26using Emby.Server.Implementations.Library;
 27using Emby.Server.Implementations.Localization;
 28using Emby.Server.Implementations.Playlists;
 29using Emby.Server.Implementations.Plugins;
 30using Emby.Server.Implementations.QuickConnect;
 31using Emby.Server.Implementations.ScheduledTasks;
 32using Emby.Server.Implementations.Serialization;
 33using Emby.Server.Implementations.Session;
 34using Emby.Server.Implementations.SyncPlay;
 35using Emby.Server.Implementations.TV;
 36using Emby.Server.Implementations.Updates;
 37using Jellyfin.Api.Helpers;
 38using Jellyfin.Drawing;
 39using Jellyfin.MediaEncoding.Hls.Playlist;
 40using Jellyfin.Networking.Manager;
 41using Jellyfin.Networking.Udp;
 42using Jellyfin.Server.Implementations;
 43using Jellyfin.Server.Implementations.MediaSegments;
 44using MediaBrowser.Common;
 45using MediaBrowser.Common.Configuration;
 46using MediaBrowser.Common.Events;
 47using MediaBrowser.Common.Net;
 48using MediaBrowser.Common.Plugins;
 49using MediaBrowser.Common.Updates;
 50using MediaBrowser.Controller;
 51using MediaBrowser.Controller.Channels;
 52using MediaBrowser.Controller.Chapters;
 53using MediaBrowser.Controller.ClientEvent;
 54using MediaBrowser.Controller.Collections;
 55using MediaBrowser.Controller.Configuration;
 56using MediaBrowser.Controller.Drawing;
 57using MediaBrowser.Controller.Dto;
 58using MediaBrowser.Controller.Entities;
 59using MediaBrowser.Controller.Library;
 60using MediaBrowser.Controller.LiveTv;
 61using MediaBrowser.Controller.Lyrics;
 62using MediaBrowser.Controller.MediaEncoding;
 63using MediaBrowser.Controller.Net;
 64using MediaBrowser.Controller.Persistence;
 65using MediaBrowser.Controller.Playlists;
 66using MediaBrowser.Controller.Providers;
 67using MediaBrowser.Controller.QuickConnect;
 68using MediaBrowser.Controller.Resolvers;
 69using MediaBrowser.Controller.Session;
 70using MediaBrowser.Controller.Sorting;
 71using MediaBrowser.Controller.Subtitles;
 72using MediaBrowser.Controller.SyncPlay;
 73using MediaBrowser.Controller.TV;
 74using MediaBrowser.LocalMetadata.Savers;
 75using MediaBrowser.MediaEncoding.BdInfo;
 76using MediaBrowser.MediaEncoding.Subtitles;
 77using MediaBrowser.MediaEncoding.Transcoding;
 78using MediaBrowser.Model.Cryptography;
 79using MediaBrowser.Model.Globalization;
 80using MediaBrowser.Model.IO;
 81using MediaBrowser.Model.MediaInfo;
 82using MediaBrowser.Model.Net;
 83using MediaBrowser.Model.Serialization;
 84using MediaBrowser.Model.System;
 85using MediaBrowser.Model.Tasks;
 86using MediaBrowser.Providers.Chapters;
 87using MediaBrowser.Providers.Lyric;
 88using MediaBrowser.Providers.Manager;
 89using MediaBrowser.Providers.Plugins.Tmdb;
 90using MediaBrowser.Providers.Subtitles;
 91using MediaBrowser.XbmcMetadata.Providers;
 92using Microsoft.AspNetCore.Http;
 93using Microsoft.AspNetCore.Mvc;
 94using Microsoft.EntityFrameworkCore;
 95using Microsoft.Extensions.Configuration;
 96using Microsoft.Extensions.DependencyInjection;
 97using Microsoft.Extensions.Logging;
 98using Prometheus.DotNetRuntime;
 99using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
 100using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager;
 101using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
 102
 103namespace Emby.Server.Implementations
 104{
 105    /// <summary>
 106    /// Class CompositionRoot.
 107    /// </summary>
 108    public abstract class ApplicationHost : IServerApplicationHost, IDisposable
 109    {
 110        /// <summary>
 111        /// The disposable parts.
 112        /// </summary>
 22113        private readonly ConcurrentBag<IDisposable> _disposableParts = new();
 114        private readonly DeviceId _deviceId;
 115
 116        private readonly IConfiguration _startupConfig;
 117        private readonly IXmlSerializer _xmlSerializer;
 118        private readonly IStartupOptions _startupOptions;
 119        private readonly PluginManager _pluginManager;
 120
 121        private List<Type> _creatingInstances;
 122
 123        /// <summary>
 124        /// Gets or sets all concrete types.
 125        /// </summary>
 126        /// <value>All concrete types.</value>
 127        private Type[] _allConcreteTypes;
 128
 129        private bool _disposed;
 130
 131        /// <summary>
 132        /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
 133        /// </summary>
 134        /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
 135        /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
 136        /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
 137        /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
 138        protected ApplicationHost(
 139            IServerApplicationPaths applicationPaths,
 140            ILoggerFactory loggerFactory,
 141            IStartupOptions options,
 142            IConfiguration startupConfig)
 143        {
 144            ApplicationPaths = applicationPaths;
 145            LoggerFactory = loggerFactory;
 22146            _startupOptions = options;
 22147            _startupConfig = startupConfig;
 148
 22149            Logger = LoggerFactory.CreateLogger<ApplicationHost>();
 22150            _deviceId = new DeviceId(ApplicationPaths, LoggerFactory.CreateLogger<DeviceId>());
 151
 22152            ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
 22153            ApplicationVersionString = ApplicationVersion.ToString(3);
 22154            ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
 155
 22156            _xmlSerializer = new MyXmlSerializer();
 22157            ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer);
 22158            _pluginManager = new PluginManager(
 22159                LoggerFactory.CreateLogger<PluginManager>(),
 22160                this,
 22161                ConfigurationManager.Configuration,
 22162                ApplicationPaths.PluginsPath,
 22163                ApplicationVersion);
 164
 22165            _disposableParts.Add(_pluginManager);
 22166        }
 167
 168        /// <summary>
 169        /// Occurs when [has pending restart changed].
 170        /// </summary>
 171        public event EventHandler HasPendingRestartChanged;
 172
 173        /// <summary>
 174        /// Gets the value of the PublishedServerUrl setting.
 175        /// </summary>
 0176        private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
 177
 178        public bool CoreStartupHasCompleted { get; private set; }
 179
 180        /// <summary>
 181        /// Gets the <see cref="INetworkManager"/> singleton instance.
 182        /// </summary>
 183        public INetworkManager NetManager { get; private set; }
 184
 185        /// <inheritdoc />
 186        public bool HasPendingRestart { get; private set; }
 187
 188        /// <inheritdoc />
 189        public bool ShouldRestart { get; set; }
 190
 191        /// <summary>
 192        /// Gets the logger.
 193        /// </summary>
 194        protected ILogger<ApplicationHost> Logger { get; }
 195
 196        /// <summary>
 197        /// Gets the logger factory.
 198        /// </summary>
 199        protected ILoggerFactory LoggerFactory { get; }
 200
 201        /// <summary>
 202        /// Gets the application paths.
 203        /// </summary>
 204        /// <value>The application paths.</value>
 205        protected IServerApplicationPaths ApplicationPaths { get; }
 206
 207        /// <summary>
 208        /// Gets the configuration manager.
 209        /// </summary>
 210        /// <value>The configuration manager.</value>
 211        public ServerConfigurationManager ConfigurationManager { get; }
 212
 213        /// <summary>
 214        /// Gets or sets the service provider.
 215        /// </summary>
 216        public IServiceProvider ServiceProvider { get; set; }
 217
 218        /// <summary>
 219        /// Gets the http port for the webhost.
 220        /// </summary>
 221        public int HttpPort { get; private set; }
 222
 223        /// <summary>
 224        /// Gets the https port for the webhost.
 225        /// </summary>
 226        public int HttpsPort { get; private set; }
 227
 228        /// <inheritdoc />
 229        public Version ApplicationVersion { get; }
 230
 231        /// <inheritdoc />
 232        public string ApplicationVersionString { get; }
 233
 234        /// <summary>
 235        /// Gets the current application user agent.
 236        /// </summary>
 237        /// <value>The application user agent.</value>
 238        public string ApplicationUserAgent { get; }
 239
 240        /// <summary>
 241        /// Gets the email address for use within a comment section of a user agent field.
 242        /// Presently used to provide contact information to MusicBrainz service.
 243        /// </summary>
 22244        public string ApplicationUserAgentAddress => "team@jellyfin.org";
 245
 246        /// <summary>
 247        /// Gets the current application name.
 248        /// </summary>
 249        /// <value>The application name.</value>
 22250        public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Locat
 251
 111252        public string SystemId => _deviceId.Value;
 253
 254        /// <inheritdoc/>
 66255        public string Name => ApplicationProductName;
 256
 257        private string CertificatePath { get; set; }
 258
 259        public X509Certificate2 Certificate { get; private set; }
 260
 261        /// <inheritdoc/>
 18262        public bool ListenWithHttps => Certificate is not null && ConfigurationManager.GetNetworkConfiguration().EnableH
 263
 264        public string FriendlyName =>
 0265            string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
 0266                ? Environment.MachineName
 0267                : ConfigurationManager.Configuration.ServerName;
 268
 269        public string ExpandVirtualPath(string path)
 270        {
 86271            var appPaths = ApplicationPaths;
 272
 86273            return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
 86274                .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIg
 275        }
 276
 277        public string ReverseVirtualPath(string path)
 278        {
 59279            var appPaths = ApplicationPaths;
 280
 59281            return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
 59282                .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIg
 283        }
 284
 285        /// <summary>
 286        /// Creates the instance safe.
 287        /// </summary>
 288        /// <param name="type">The type.</param>
 289        /// <returns>System.Object.</returns>
 290        protected object CreateInstanceSafe(Type type)
 291        {
 4048292            _creatingInstances ??= new List<Type>();
 293
 4048294            if (_creatingInstances.Contains(type))
 295            {
 0296                Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
 0297                foreach (var entry in _creatingInstances)
 298                {
 0299                    Logger.LogError("Called from: {TypeName}", entry.FullName);
 300                }
 301
 0302                _pluginManager.FailPlugin(type.Assembly);
 303
 0304                throw new TypeLoadException("DI Loop detected");
 305            }
 306
 307            try
 308            {
 4048309                _creatingInstances.Add(type);
 4048310                Logger.LogDebug("Creating instance of {Type}", type);
 4048311                return ServiceProvider is null
 4048312                    ? Activator.CreateInstance(type)
 4048313                    : ActivatorUtilities.CreateInstance(ServiceProvider, type);
 314            }
 0315            catch (Exception ex)
 316            {
 0317                Logger.LogError(ex, "Error creating {Type}", type);
 318                // If this is a plugin fail it.
 0319                _pluginManager.FailPlugin(type.Assembly);
 0320                return null;
 321            }
 322            finally
 323            {
 4048324                _creatingInstances.Remove(type);
 4048325            }
 4048326        }
 327
 328        /// <summary>
 329        /// Resolves this instance.
 330        /// </summary>
 331        /// <typeparam name="T">The type.</typeparam>
 332        /// <returns>``0.</returns>
 506333        public T Resolve<T>() => ServiceProvider.GetService<T>();
 334
 335        /// <inheritdoc/>
 336        public IEnumerable<Type> GetExportTypes<T>()
 337        {
 338            var currentType = typeof(T);
 339            var numberOfConcreteTypes = _allConcreteTypes.Length;
 340            for (var i = 0; i < numberOfConcreteTypes; i++)
 341            {
 342                var type = _allConcreteTypes[i];
 343                if (currentType.IsAssignableFrom(type))
 344                {
 345                    yield return type;
 346                }
 347            }
 348        }
 349
 350        /// <inheritdoc />
 351        public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
 352        {
 353            // Convert to list so this isn't executed for each iteration
 308354            var parts = GetExportTypes<T>()
 308355                .Select(CreateInstanceSafe)
 308356                .Where(i => i is not null)
 308357                .Cast<T>()
 308358                .ToList();
 359
 308360            if (manageLifetime)
 361            {
 660362                foreach (var part in parts.OfType<IDisposable>())
 363                {
 44364                    _disposableParts.Add(part);
 365                }
 366            }
 367
 308368            return parts;
 369        }
 370
 371        /// <inheritdoc />
 372        public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
 373        {
 374            // Convert to list so this isn't executed for each iteration
 22375            var parts = GetExportTypes<T>()
 22376                .Select(i => defaultFunc(i))
 22377                .Where(i => i is not null)
 22378                .Cast<T>()
 22379                .ToList();
 380
 22381            if (manageLifetime)
 382            {
 44383                foreach (var part in parts.OfType<IDisposable>())
 384                {
 0385                    _disposableParts.Add(part);
 386                }
 387            }
 388
 22389            return parts;
 390        }
 391
 392        /// <summary>
 393        /// Runs the startup tasks.
 394        /// </summary>
 395        /// <returns><see cref="Task" />.</returns>
 396        public Task RunStartupTasksAsync()
 397        {
 22398            Logger.LogInformation("Running startup tasks");
 399
 22400            Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
 401
 22402            ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
 22403            ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
 404
 22405            var ffmpegValid = Resolve<IMediaEncoder>().SetFFmpegPath();
 406
 22407            if (!ffmpegValid)
 408            {
 0409                throw new FfmpegException("Failed to find valid ffmpeg");
 410            }
 411
 22412            Logger.LogInformation("ServerId: {ServerId}", SystemId);
 22413            Logger.LogInformation("Core startup complete");
 22414            CoreStartupHasCompleted = true;
 415
 22416            return Task.CompletedTask;
 417        }
 418
 419        /// <inheritdoc/>
 420        public void Init(IServiceCollection serviceCollection)
 421        {
 22422            DiscoverTypes();
 423
 22424            ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
 425
 22426            NetManager = new NetworkManager(ConfigurationManager, _startupConfig, LoggerFactory.CreateLogger<NetworkMana
 427
 428            // Initialize runtime stat collection
 22429            if (ConfigurationManager.Configuration.EnableMetrics)
 430            {
 0431                _disposableParts.Add(DotNetRuntimeStatsBuilder.Default().StartCollecting());
 432            }
 433
 22434            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 22435            HttpPort = networkConfiguration.InternalHttpPort;
 22436            HttpsPort = networkConfiguration.InternalHttpsPort;
 437
 438            // Safeguard against invalid configuration
 22439            if (HttpPort == HttpsPort)
 440            {
 0441                HttpPort = NetworkConfiguration.DefaultHttpPort;
 0442                HttpsPort = NetworkConfiguration.DefaultHttpsPort;
 443            }
 444
 22445            CertificatePath = networkConfiguration.CertificatePath;
 22446            Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
 447
 22448            RegisterServices(serviceCollection);
 449
 22450            _pluginManager.RegisterServices(serviceCollection);
 22451        }
 452
 453        /// <summary>
 454        /// Registers services/resources with the service collection that will be available via DI.
 455        /// </summary>
 456        /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
 457        protected virtual void RegisterServices(IServiceCollection serviceCollection)
 458        {
 22459            serviceCollection.AddSingleton(_startupOptions);
 460
 22461            serviceCollection.AddMemoryCache();
 462
 22463            serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
 22464            serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
 22465            serviceCollection.AddSingleton<IApplicationHost>(this);
 22466            serviceCollection.AddSingleton<IPluginManager>(_pluginManager);
 22467            serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
 468
 22469            serviceCollection.AddSingleton<IFileSystem, ManagedFileSystem>();
 22470            serviceCollection.AddSingleton<IShortcutHandler, MbLinkShortcutHandler>();
 471
 22472            serviceCollection.AddScoped<ISystemManager, SystemManager>();
 473
 22474            serviceCollection.AddSingleton<TmdbClientManager>();
 475
 22476            serviceCollection.AddSingleton(NetManager);
 477
 22478            serviceCollection.AddSingleton<ITaskManager, TaskManager>();
 479
 22480            serviceCollection.AddSingleton(_xmlSerializer);
 481
 22482            serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
 483
 22484            serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
 485
 22486            serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
 487
 22488            serviceCollection.AddSingleton<IServerApplicationHost>(this);
 22489            serviceCollection.AddSingleton(ApplicationPaths);
 490
 22491            serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
 492
 22493            serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
 494
 22495            serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
 22496            serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
 497
 22498            serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
 499
 22500            serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
 22501            serviceCollection.AddSingleton<EncodingHelper>();
 502
 503            // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
 22504            serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMon
 22505            serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderM
 22506            serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewM
 22507            serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
 22508            serviceCollection.AddSingleton<NamingOptions>();
 509
 22510            serviceCollection.AddSingleton<IMusicManager, MusicManager>();
 511
 22512            serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
 513
 22514            serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
 515
 22516            serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
 517
 22518            serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
 519
 22520            serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
 521
 22522            serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
 523
 22524            serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
 22525            serviceCollection.AddSingleton<ILyricManager, LyricManager>();
 526
 22527            serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
 528
 529            // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
 22530            serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManag
 22531            serviceCollection.AddSingleton<IDtoService, DtoService>();
 532
 22533            serviceCollection.AddSingleton<ISessionManager, SessionManager>();
 534
 22535            serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
 536
 22537            serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
 538
 22539            serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
 540
 22541            serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
 542
 22543            serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
 544
 22545            serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
 546
 22547            serviceCollection.AddSingleton<IAuthService, AuthService>();
 22548            serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
 549
 22550            serviceCollection.AddSingleton<ISubtitleParser, SubtitleEditParser>();
 22551            serviceCollection.AddSingleton<ISubtitleEncoder, SubtitleEncoder>();
 552
 22553            serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtrac
 554
 22555            serviceCollection.AddSingleton<ITranscodeManager, TranscodeManager>();
 22556            serviceCollection.AddScoped<MediaInfoHelper>();
 22557            serviceCollection.AddScoped<AudioHelper>();
 22558            serviceCollection.AddScoped<DynamicHlsHelper>();
 22559            serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
 22560            serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
 561
 22562            serviceCollection.AddSingleton<IMediaSegmentManager, MediaSegmentManager>();
 22563        }
 564
 565        /// <summary>
 566        /// Create services registered with the service container that need to be initialized at application startup.
 567        /// </summary>
 568        /// <returns>A task representing the service initialization operation.</returns>
 569        public async Task InitializeServices()
 570        {
 571            var jellyfinDb = await Resolve<IDbContextFactory<JellyfinDbContext>>().CreateDbContextAsync().ConfigureAwait
 572            await using (jellyfinDb.ConfigureAwait(false))
 573            {
 574                if ((await jellyfinDb.Database.GetPendingMigrationsAsync().ConfigureAwait(false)).Any())
 575                {
 576                    Logger.LogInformation("There are pending EFCore migrations in the database. Applying... (This may ta
 577                    await jellyfinDb.Database.MigrateAsync().ConfigureAwait(false);
 578                    Logger.LogInformation("EFCore migrations applied successfully");
 579                }
 580            }
 581
 582            ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize();
 583            ((SqliteUserDataRepository)Resolve<IUserDataRepository>()).Initialize();
 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        {
 22595            if (string.IsNullOrWhiteSpace(path))
 596            {
 22597                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 = new X509Certificate2(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
 22632            BaseItem.Logger = Resolve<ILogger<BaseItem>>();
 22633            BaseItem.ConfigurationManager = ConfigurationManager;
 22634            BaseItem.LibraryManager = Resolve<ILibraryManager>();
 22635            BaseItem.ProviderManager = Resolve<IProviderManager>();
 22636            BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
 22637            BaseItem.ItemRepository = Resolve<IItemRepository>();
 22638            BaseItem.FileSystem = Resolve<IFileSystem>();
 22639            BaseItem.UserDataManager = Resolve<IUserDataManager>();
 22640            BaseItem.ChannelManager = Resolve<IChannelManager>();
 22641            Video.RecordingsManager = Resolve<IRecordingsManager>();
 22642            Folder.UserViewManager = Resolve<IUserViewManager>();
 22643            UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
 22644            UserView.CollectionManager = Resolve<ICollectionManager>();
 22645            BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
 22646            BaseItem.MediaSegmentManager = Resolve<IMediaSegmentManager>();
 22647            CollectionFolder.XmlSerializer = _xmlSerializer;
 22648            CollectionFolder.ApplicationHost = this;
 22649        }
 650
 651        /// <summary>
 652        /// Finds plugin components and register them with the appropriate services.
 653        /// </summary>
 654        private void FindParts()
 655        {
 22656            if (!ConfigurationManager.Configuration.IsPortAuthorized)
 657            {
 22658                ConfigurationManager.Configuration.IsPortAuthorized = true;
 22659                ConfigurationManager.SaveConfiguration();
 660            }
 661
 22662            _pluginManager.CreatePlugins();
 663
 22664            Resolve<ILibraryManager>().AddParts(
 22665                GetExports<IResolverIgnoreRule>(),
 22666                GetExports<IItemResolver>(),
 22667                GetExports<IIntroProvider>(),
 22668                GetExports<IBaseItemComparer>(),
 22669                GetExports<ILibraryPostScanTask>());
 670
 22671            Resolve<IProviderManager>().AddParts(
 22672                GetExports<IImageProvider>(),
 22673                GetExports<IMetadataService>(),
 22674                GetExports<IMetadataProvider>(),
 22675                GetExports<IMetadataSaver>(),
 22676                GetExports<IExternalId>(),
 22677                GetExports<IExternalUrlProvider>());
 678
 22679            Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
 22680        }
 681
 682        /// <summary>
 683        /// Discovers the types.
 684        /// </summary>
 685        protected void DiscoverTypes()
 686        {
 22687            Logger.LogInformation("Loading assemblies");
 688
 22689            _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
 22690        }
 691
 692        private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
 693        {
 694            foreach (var ass in assemblies)
 695            {
 696                Type[] exportedTypes;
 697                try
 698                {
 699                    exportedTypes = ass.GetExportedTypes();
 700                }
 701                catch (FileNotFoundException ex)
 702                {
 703                    Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
 704                    _pluginManager.FailPlugin(ass);
 705                    continue;
 706                }
 707                catch (TypeLoadException ex)
 708                {
 709                    Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
 710                    _pluginManager.FailPlugin(ass);
 711                    continue;
 712                }
 713
 714                foreach (Type type in exportedTypes)
 715                {
 716                    if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
 717                    {
 718                        yield return type;
 719                    }
 720                }
 721            }
 722        }
 723
 724        /// <summary>
 725        /// Called when [configuration updated].
 726        /// </summary>
 727        /// <param name="sender">The sender.</param>
 728        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 729        private void OnConfigurationUpdated(object sender, EventArgs e)
 730        {
 19731            var requiresRestart = false;
 19732            var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
 733
 734            // Don't do anything if these haven't been set yet
 19735            if (HttpPort != 0 && HttpsPort != 0)
 736            {
 737                // Need to restart if ports have changed
 19738                if (networkConfiguration.InternalHttpPort != HttpPort
 19739                    || networkConfiguration.InternalHttpsPort != HttpsPort)
 740                {
 0741                    if (ConfigurationManager.Configuration.IsPortAuthorized)
 742                    {
 0743                        ConfigurationManager.Configuration.IsPortAuthorized = false;
 0744                        ConfigurationManager.SaveConfiguration();
 745
 0746                        requiresRestart = true;
 747                    }
 748                }
 749            }
 750
 19751            if (ValidateSslCertificate(networkConfiguration))
 752            {
 0753                requiresRestart = true;
 754            }
 755
 19756            if (requiresRestart)
 757            {
 0758                Logger.LogInformation("App needs to be restarted due to configuration change.");
 759
 0760                NotifyPendingRestart();
 761            }
 19762        }
 763
 764        /// <summary>
 765        /// Validates the SSL certificate.
 766        /// </summary>
 767        /// <param name="networkConfig">The new configuration.</param>
 768        /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
 769        private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
 770        {
 19771            var newPath = networkConfig.CertificatePath;
 772
 19773            if (!string.IsNullOrWhiteSpace(newPath)
 19774                && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
 775            {
 0776                if (File.Exists(newPath))
 777                {
 0778                    return true;
 779                }
 780
 0781                throw new FileNotFoundException(
 0782                    string.Format(
 0783                        CultureInfo.InvariantCulture,
 0784                        "Certificate file '{0}' does not exist.",
 0785                        newPath));
 786            }
 787
 19788            return false;
 789        }
 790
 791        /// <summary>
 792        /// Notifies the kernel that a change has been made that requires a restart.
 793        /// </summary>
 794        public void NotifyPendingRestart()
 795        {
 0796            Logger.LogInformation("App needs to be restarted.");
 797
 0798            var changed = !HasPendingRestart;
 799
 0800            HasPendingRestart = true;
 801
 0802            if (changed)
 803            {
 0804                EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
 805            }
 0806        }
 807
 808        /// <summary>
 809        /// Gets the composable part assemblies.
 810        /// </summary>
 811        /// <returns>IEnumerable{Assembly}.</returns>
 812        protected IEnumerable<Assembly> GetComposablePartAssemblies()
 813        {
 814            foreach (var p in _pluginManager.LoadAssemblies())
 815            {
 816                yield return p;
 817            }
 818
 819            // Include composable parts in the Model assembly
 820            yield return typeof(SystemInfo).Assembly;
 821
 822            // Include composable parts in the Common assembly
 823            yield return typeof(IApplicationHost).Assembly;
 824
 825            // Include composable parts in the Controller assembly
 826            yield return typeof(IServerApplicationHost).Assembly;
 827
 828            // Include composable parts in the Providers assembly
 829            yield return typeof(ProviderManager).Assembly;
 830
 831            // Include composable parts in the Photos assembly
 832            yield return typeof(PhotoProvider).Assembly;
 833
 834            // Emby.Server implementations
 835            yield return typeof(InstallationManager).Assembly;
 836
 837            // MediaEncoding
 838            yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
 839
 840            // Local metadata
 841            yield return typeof(BoxSetXmlSaver).Assembly;
 842
 843            // Xbmc
 844            yield return typeof(ArtistNfoProvider).Assembly;
 845
 846            // Network
 847            yield return typeof(NetworkManager).Assembly;
 848
 849            // Hls
 850            yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
 851
 852            foreach (var i in GetAssembliesWithPartsInternal())
 853            {
 854                yield return i;
 855            }
 856        }
 857
 858        protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
 859
 860        /// <inheritdoc/>
 861        public string GetSmartApiUrl(IPAddress remoteAddr)
 862        {
 863            // Published server ends with a /
 0864            if (!string.IsNullOrEmpty(PublishedServerUrl))
 865            {
 866                // Published server ends with a '/', so we need to remove it.
 0867                return PublishedServerUrl.Trim('/');
 868            }
 869
 0870            string smart = NetManager.GetBindAddress(remoteAddr, out var port);
 0871            return GetLocalApiUrl(smart.Trim('/'), null, port);
 872        }
 873
 874        /// <inheritdoc/>
 875        public string GetSmartApiUrl(HttpRequest request)
 876        {
 877            // Return the host in the HTTP request as the API URL if not configured otherwise
 0878            if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
 879            {
 0880                int? requestPort = request.Host.Port;
 0881                if (requestPort is null
 0882                    || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
 0883                    || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)
 884                {
 0885                    requestPort = -1;
 886                }
 887
 0888                return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
 889            }
 890
 0891            return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
 892        }
 893
 894        /// <inheritdoc/>
 895        public string GetSmartApiUrl(string hostname)
 896        {
 897            // Published server ends with a /
 0898            if (!string.IsNullOrEmpty(PublishedServerUrl))
 899            {
 900                // Published server ends with a '/', so we need to remove it.
 0901                return PublishedServerUrl.Trim('/');
 902            }
 903
 0904            string smart = NetManager.GetBindAddress(hostname, out var port);
 0905            return GetLocalApiUrl(smart.Trim('/'), null, port);
 906        }
 907
 908        /// <inheritdoc/>
 909        public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
 910        {
 911            // With an empty source, the port will be null
 0912            var smart = NetManager.GetBindAddress(ipAddress, out _, false);
 0913            var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
 0914            int? port = !allowHttps ? HttpPort : null;
 0915            return GetLocalApiUrl(smart, scheme, port);
 916        }
 917
 918        /// <inheritdoc/>
 919        public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
 920        {
 921            // If the smartAPI doesn't start with http then treat it as a host or ip.
 0922            if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
 923            {
 0924                return hostname.TrimEnd('/');
 925            }
 926
 927            // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
 928            // not. For consistency, always trim the trailing slash.
 0929            scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
 0930            var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
 0931            return new UriBuilder
 0932            {
 0933                Scheme = scheme,
 0934                Host = hostname,
 0935                Port = port ?? (isHttps ? HttpsPort : HttpPort),
 0936                Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
 0937            }.ToString().TrimEnd('/');
 938        }
 939
 940        public IEnumerable<Assembly> GetApiPluginAssemblies()
 941        {
 942            var assemblies = _allConcreteTypes
 943                .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
 944                .Select(i => i.Assembly)
 945                .Distinct();
 946
 947            foreach (var assembly in assemblies)
 948            {
 949                Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
 950                yield return assembly;
 951            }
 952        }
 953
 954        /// <inheritdoc />
 955        public void Dispose()
 956        {
 22957            Dispose(true);
 22958            GC.SuppressFinalize(this);
 22959        }
 960
 961        /// <summary>
 962        /// Releases unmanaged and - optionally - managed resources.
 963        /// </summary>
 964        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 965        protected virtual void Dispose(bool dispose)
 966        {
 22967            if (_disposed)
 968            {
 0969                return;
 970            }
 971
 22972            if (dispose)
 973            {
 22974                var type = GetType();
 975
 22976                Logger.LogInformation("Disposing {Type}", type.Name);
 977
 176978                foreach (var part in _disposableParts.ToArray())
 979                {
 66980                    var partType = part.GetType();
 66981                    if (partType == type)
 982                    {
 983                        continue;
 984                    }
 985
 66986                    Logger.LogInformation("Disposing {Type}", partType.Name);
 987
 988                    try
 989                    {
 66990                        part.Dispose();
 66991                    }
 0992                    catch (Exception ex)
 993                    {
 0994                        Logger.LogError(ex, "Error disposing {Type}", partType.Name);
 0995                    }
 996                }
 997
 22998                _disposableParts.Clear();
 999            }
 1000
 221001            _disposed = true;
 221002        }
 1003    }
 1004}