ApplicationHost.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Reflection;
  11. using System.Runtime.InteropServices;
  12. using System.Security.Cryptography.X509Certificates;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using Emby.Dlna;
  17. using Emby.Dlna.Common;
  18. using Emby.Drawing;
  19. using Emby.Notifications;
  20. using Emby.Photos;
  21. using Emby.Server.Implementations.Archiving;
  22. using Emby.Server.Implementations.Channels;
  23. using Emby.Server.Implementations.Collections;
  24. using Emby.Server.Implementations.Configuration;
  25. using Emby.Server.Implementations.Cryptography;
  26. using Emby.Server.Implementations.Data;
  27. using Emby.Server.Implementations.Devices;
  28. using Emby.Server.Implementations.Dto;
  29. using Emby.Server.Implementations.HttpServer.Security;
  30. using Emby.Server.Implementations.IO;
  31. using Emby.Server.Implementations.Library;
  32. using Emby.Server.Implementations.LiveTv;
  33. using Emby.Server.Implementations.Localization;
  34. using Emby.Server.Implementations.Playlists;
  35. using Emby.Server.Implementations.Plugins;
  36. using Emby.Server.Implementations.QuickConnect;
  37. using Emby.Server.Implementations.ScheduledTasks;
  38. using Emby.Server.Implementations.Security;
  39. using Emby.Server.Implementations.Serialization;
  40. using Emby.Server.Implementations.Session;
  41. using Emby.Server.Implementations.SyncPlay;
  42. using Emby.Server.Implementations.TV;
  43. using Emby.Server.Implementations.Updates;
  44. using Jellyfin.Api.Helpers;
  45. using Jellyfin.Networking.Advertising;
  46. using Jellyfin.Networking.Gateway;
  47. using Jellyfin.Networking.Manager;
  48. using Jellyfin.Networking.UPnP;
  49. using MediaBrowser.Common;
  50. using MediaBrowser.Common.Configuration;
  51. using MediaBrowser.Common.Events;
  52. using MediaBrowser.Common.Net;
  53. using MediaBrowser.Common.Plugins;
  54. using MediaBrowser.Common.Updates;
  55. using MediaBrowser.Controller;
  56. using MediaBrowser.Controller.Channels;
  57. using MediaBrowser.Controller.Chapters;
  58. using MediaBrowser.Controller.Collections;
  59. using MediaBrowser.Controller.Configuration;
  60. using MediaBrowser.Controller.Devices;
  61. using MediaBrowser.Controller.Drawing;
  62. using MediaBrowser.Controller.Dto;
  63. using MediaBrowser.Controller.Entities;
  64. using MediaBrowser.Controller.Library;
  65. using MediaBrowser.Controller.LiveTv;
  66. using MediaBrowser.Controller.MediaEncoding;
  67. using MediaBrowser.Controller.Net;
  68. using MediaBrowser.Controller.Notifications;
  69. using MediaBrowser.Controller.Persistence;
  70. using MediaBrowser.Controller.Playlists;
  71. using MediaBrowser.Controller.Plugins;
  72. using MediaBrowser.Controller.Providers;
  73. using MediaBrowser.Controller.QuickConnect;
  74. using MediaBrowser.Controller.Resolvers;
  75. using MediaBrowser.Controller.Security;
  76. using MediaBrowser.Controller.Session;
  77. using MediaBrowser.Controller.Sorting;
  78. using MediaBrowser.Controller.Subtitles;
  79. using MediaBrowser.Controller.SyncPlay;
  80. using MediaBrowser.Controller.TV;
  81. using MediaBrowser.LocalMetadata.Savers;
  82. using MediaBrowser.MediaEncoding.BdInfo;
  83. using MediaBrowser.Model.Configuration;
  84. using MediaBrowser.Model.Cryptography;
  85. using MediaBrowser.Model.Globalization;
  86. using MediaBrowser.Model.IO;
  87. using MediaBrowser.Model.MediaInfo;
  88. using MediaBrowser.Model.Serialization;
  89. using MediaBrowser.Model.System;
  90. using MediaBrowser.Model.Tasks;
  91. using MediaBrowser.Providers.Chapters;
  92. using MediaBrowser.Providers.Manager;
  93. using MediaBrowser.Providers.Plugins.TheTvdb;
  94. using MediaBrowser.Providers.Subtitles;
  95. using MediaBrowser.XbmcMetadata.Providers;
  96. using Microsoft.AspNetCore.Http;
  97. using Microsoft.AspNetCore.Mvc;
  98. using Microsoft.Extensions.DependencyInjection;
  99. using Microsoft.Extensions.Logging;
  100. using Prometheus.DotNetRuntime;
  101. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  102. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  103. namespace Emby.Server.Implementations
  104. {
  105. /// <summary>
  106. /// Class CompositionRoot.
  107. /// </summary>
  108. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  109. {
  110. /// <summary>
  111. /// The environment variable prefixes to log at server startup.
  112. /// </summary>
  113. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  114. private readonly IFileSystem _fileSystemManager;
  115. private readonly IXmlSerializer _xmlSerializer;
  116. private readonly IJsonSerializer _jsonSerializer;
  117. private readonly IStartupOptions _startupOptions;
  118. private IMediaEncoder _mediaEncoder;
  119. private ISessionManager _sessionManager;
  120. private IHttpClientFactory _httpClientFactory;
  121. private IWebSocketManager _webSocketManager;
  122. private string[] _urlPrefixes;
  123. /// <summary>
  124. /// Gets a value indicating whether this instance can self restart.
  125. /// </summary>
  126. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  127. public bool CoreStartupHasCompleted { get; private set; }
  128. public virtual bool CanLaunchWebBrowser
  129. {
  130. get
  131. {
  132. if (!Environment.UserInteractive)
  133. {
  134. return false;
  135. }
  136. if (_startupOptions.IsService)
  137. {
  138. return false;
  139. }
  140. if (OperatingSystem.Id == OperatingSystemId.Windows
  141. || OperatingSystem.Id == OperatingSystemId.Darwin)
  142. {
  143. return true;
  144. }
  145. return false;
  146. }
  147. }
  148. /// <summary>
  149. /// Occurs when [has pending restart changed].
  150. /// </summary>
  151. public event EventHandler HasPendingRestartChanged;
  152. /// <summary>
  153. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  154. /// </summary>
  155. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  156. public bool HasPendingRestart { get; private set; }
  157. /// <inheritdoc />
  158. public bool IsShuttingDown { get; private set; }
  159. /// <summary>
  160. /// Gets the logger.
  161. /// </summary>
  162. protected ILogger<ApplicationHost> Logger { get; }
  163. protected IServiceCollection ServiceCollection { get; }
  164. private IPlugin[] _plugins;
  165. /// <summary>
  166. /// Gets the plugins.
  167. /// </summary>
  168. /// <value>The plugins.</value>
  169. public IReadOnlyList<IPlugin> Plugins => _plugins;
  170. /// <summary>
  171. /// Gets the logger factory.
  172. /// </summary>
  173. protected ILoggerFactory LoggerFactory { get; }
  174. /// <summary>
  175. /// Gets or sets the application paths.
  176. /// </summary>
  177. /// <value>The application paths.</value>
  178. protected IServerApplicationPaths ApplicationPaths { get; set; }
  179. /// <summary>
  180. /// Gets or sets all concrete types.
  181. /// </summary>
  182. /// <value>All concrete types.</value>
  183. private Type[] _allConcreteTypes;
  184. /// <summary>
  185. /// The disposable parts.
  186. /// </summary>
  187. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  188. /// <summary>
  189. /// Gets or sets the configuration manager.
  190. /// </summary>
  191. /// <value>The configuration manager.</value>
  192. protected IConfigurationManager ConfigurationManager { get; set; }
  193. /// <summary>
  194. /// Gets or sets the service provider.
  195. /// </summary>
  196. public IServiceProvider ServiceProvider { get; set; }
  197. /// <summary>
  198. /// Gets the http port for the webhost.
  199. /// </summary>
  200. public int HttpPort { get; private set; }
  201. /// <summary>
  202. /// Gets the https port for the webhost.
  203. /// </summary>
  204. public int HttpsPort { get; private set; }
  205. /// <summary>
  206. /// Gets the server configuration manager.
  207. /// </summary>
  208. /// <value>The server configuration manager.</value>
  209. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  210. /// <summary>
  211. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  212. /// </summary>
  213. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  214. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  215. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  216. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  217. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  218. public ApplicationHost(
  219. IServerApplicationPaths applicationPaths,
  220. ILoggerFactory loggerFactory,
  221. IStartupOptions options,
  222. IFileSystem fileSystem,
  223. IServiceCollection serviceCollection)
  224. {
  225. _xmlSerializer = new MyXmlSerializer();
  226. _jsonSerializer = new JsonSerializer();
  227. ServiceCollection = serviceCollection;
  228. ApplicationPaths = applicationPaths;
  229. LoggerFactory = loggerFactory;
  230. _fileSystemManager = fileSystem;
  231. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  232. NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
  233. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  234. _startupOptions = options;
  235. // Initialize runtime stat collection
  236. if (ServerConfigurationManager.Configuration.EnableMetrics)
  237. {
  238. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  239. }
  240. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  241. CertificateInfo = new CertificateInfo
  242. {
  243. Path = ServerConfigurationManager.Configuration.CertificatePath,
  244. Password = ServerConfigurationManager.Configuration.CertificatePassword
  245. };
  246. Certificate = GetCertificate(CertificateInfo);
  247. }
  248. /// <summary>
  249. /// Gets the NetworkManager instance.
  250. /// </summary>
  251. public INetworkManager NetManager { get; internal set; }
  252. public string ExpandVirtualPath(string path)
  253. {
  254. var appPaths = ApplicationPaths;
  255. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  256. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  257. }
  258. public string ReverseVirtualPath(string path)
  259. {
  260. var appPaths = ApplicationPaths;
  261. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  262. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  263. }
  264. /// <inheritdoc />
  265. public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version;
  266. /// <inheritdoc />
  267. public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  268. /// <summary>
  269. /// Gets the current application user agent.
  270. /// </summary>
  271. /// <value>The application user agent.</value>
  272. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  273. /// <summary>
  274. /// Gets the email address for use within a comment section of a user agent field.
  275. /// Presently used to provide contact information to MusicBrainz service.
  276. /// </summary>
  277. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  278. /// <summary>
  279. /// Gets the current application name.
  280. /// </summary>
  281. /// <value>The application name.</value>
  282. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  283. private DeviceId _deviceId;
  284. public string SystemId
  285. {
  286. get
  287. {
  288. if (_deviceId == null)
  289. {
  290. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  291. }
  292. return _deviceId.Value;
  293. }
  294. }
  295. /// <inheritdoc/>
  296. public string Name => ApplicationProductName;
  297. /// <summary>
  298. /// Creates an instance of type and resolves all constructor dependencies.
  299. /// </summary>
  300. /// <param name="type">The type.</param>
  301. /// <returns>System.Object.</returns>
  302. public object CreateInstance(Type type)
  303. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  304. /// <summary>
  305. /// Creates an instance of type and resolves all constructor dependencies.
  306. /// </summary>
  307. /// /// <typeparam name="T">The type.</typeparam>
  308. /// <returns>T.</returns>
  309. public T CreateInstance<T>()
  310. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  311. /// <summary>
  312. /// Creates the instance safe.
  313. /// </summary>
  314. /// <param name="type">The type.</param>
  315. /// <returns>System.Object.</returns>
  316. protected object CreateInstanceSafe(Type type)
  317. {
  318. try
  319. {
  320. Logger.LogDebug("Creating instance of {Type}", type);
  321. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  322. }
  323. catch (Exception ex)
  324. {
  325. Logger.LogError(ex, "Error creating {Type}", type);
  326. return null;
  327. }
  328. }
  329. /// <summary>
  330. /// Resolves this instance.
  331. /// </summary>
  332. /// <typeparam name="T">The type.</typeparam>
  333. /// <returns>``0.</returns>
  334. public T Resolve<T>() => ServiceProvider.GetService<T>();
  335. /// <summary>
  336. /// Gets the export types.
  337. /// </summary>
  338. /// <typeparam name="T">The type.</typeparam>
  339. /// <returns>IEnumerable{Type}.</returns>
  340. public IEnumerable<Type> GetExportTypes<T>()
  341. {
  342. var currentType = typeof(T);
  343. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  344. }
  345. /// <inheritdoc />
  346. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  347. {
  348. // Convert to list so this isn't executed for each iteration
  349. var parts = GetExportTypes<T>()
  350. .Select(CreateInstanceSafe)
  351. .Where(i => i != null)
  352. .Cast<T>()
  353. .ToList();
  354. if (manageLifetime)
  355. {
  356. lock (_disposableParts)
  357. {
  358. _disposableParts.AddRange(parts.OfType<IDisposable>());
  359. }
  360. }
  361. return parts;
  362. }
  363. /// <summary>
  364. /// Runs the startup tasks.
  365. /// </summary>
  366. /// <returns><see cref="Task" />.</returns>
  367. public async Task RunStartupTasksAsync()
  368. {
  369. Logger.LogInformation("Running startup tasks");
  370. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  371. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  372. _mediaEncoder.SetFFmpegPath();
  373. Logger.LogInformation("ServerId: {0}", SystemId);
  374. var entryPoints = GetExports<IServerEntryPoint>();
  375. var stopWatch = new Stopwatch();
  376. stopWatch.Start();
  377. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  378. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  379. Logger.LogInformation("Core startup complete");
  380. CoreStartupHasCompleted = true;
  381. stopWatch.Restart();
  382. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  383. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  384. stopWatch.Stop();
  385. }
  386. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  387. {
  388. foreach (var entryPoint in entryPoints)
  389. {
  390. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  391. {
  392. continue;
  393. }
  394. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  395. yield return entryPoint.RunAsync();
  396. }
  397. }
  398. /// <inheritdoc/>
  399. public void Init()
  400. {
  401. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  402. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  403. // Safeguard against invalid configuration
  404. if (HttpPort == HttpsPort)
  405. {
  406. HttpPort = ServerConfiguration.DefaultHttpPort;
  407. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  408. }
  409. DiscoverTypes();
  410. RegisterServices();
  411. }
  412. /// <summary>
  413. /// Registers services/resources with the service collection that will be available via DI.
  414. /// </summary>
  415. protected virtual void RegisterServices()
  416. {
  417. ServiceCollection.AddSingleton(_startupOptions);
  418. ServiceCollection.AddMemoryCache();
  419. ServiceCollection.AddSingleton(ConfigurationManager);
  420. ServiceCollection.AddSingleton<IApplicationHost>(this);
  421. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  422. ServiceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  423. ServiceCollection.AddSingleton(_fileSystemManager);
  424. ServiceCollection.AddSingleton<TvdbClientManager>();
  425. ServiceCollection.AddSingleton(NetManager);
  426. ServiceCollection.AddSingleton<GatewayMonitor>();
  427. ServiceCollection.AddSingleton<WhoIsJellyfinServer>();
  428. ServiceCollection.AddSingleton<ExternalPortForwarding>();
  429. ServiceCollection.AddSingleton<IIsoManager, IsoManager>();
  430. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  431. ServiceCollection.AddSingleton(_xmlSerializer);
  432. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  433. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  434. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  435. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  436. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  437. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  438. ServiceCollection.AddSingleton(ServerConfigurationManager);
  439. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  440. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  441. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  442. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  443. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  444. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  445. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  446. ServiceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  447. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  448. ServiceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  449. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  450. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  451. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  452. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  453. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  454. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  455. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  456. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  457. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  458. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  459. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  460. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  461. ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  462. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  463. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  464. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  465. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  466. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  467. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  468. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  469. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  470. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  471. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  472. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  473. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  474. ServiceCollection.AddSingleton<LiveTvDtoService>();
  475. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  476. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  477. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  478. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  479. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  480. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  481. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  482. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  483. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  484. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  485. ServiceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  486. ServiceCollection.AddSingleton<EncodingHelper>();
  487. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  488. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  489. ServiceCollection.AddScoped<MediaInfoHelper>();
  490. ServiceCollection.AddScoped<AudioHelper>();
  491. ServiceCollection.AddScoped<DynamicHlsHelper>();
  492. }
  493. /// <summary>
  494. /// Create services registered with the service container that need to be initialized at application startup.
  495. /// </summary>
  496. /// <returns>A task representing the service initialization operation.</returns>
  497. public async Task InitializeServices()
  498. {
  499. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  500. await localizationManager.LoadAll().ConfigureAwait(false);
  501. _mediaEncoder = Resolve<IMediaEncoder>();
  502. _sessionManager = Resolve<ISessionManager>();
  503. _httpClientFactory = Resolve<IHttpClientFactory>();
  504. _webSocketManager = Resolve<IWebSocketManager>();
  505. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  506. SetStaticProperties();
  507. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  508. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  509. FindParts();
  510. }
  511. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  512. {
  513. // Distinct these to prevent users from reporting problems that aren't actually problems
  514. var commandLineArgs = Environment
  515. .GetCommandLineArgs()
  516. .Distinct();
  517. // Get all relevant environment variables
  518. var allEnvVars = Environment.GetEnvironmentVariables();
  519. var relevantEnvVars = new Dictionary<object, object>();
  520. foreach (var key in allEnvVars.Keys)
  521. {
  522. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  523. {
  524. relevantEnvVars.Add(key, allEnvVars[key]);
  525. }
  526. }
  527. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  528. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  529. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  530. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  531. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  532. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  533. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  534. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  535. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  536. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  537. }
  538. private X509Certificate2 GetCertificate(CertificateInfo info)
  539. {
  540. var certificateLocation = info?.Path;
  541. if (string.IsNullOrWhiteSpace(certificateLocation))
  542. {
  543. return null;
  544. }
  545. try
  546. {
  547. if (!File.Exists(certificateLocation))
  548. {
  549. return null;
  550. }
  551. // Don't use an empty string password
  552. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  553. var localCert = new X509Certificate2(certificateLocation, password);
  554. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  555. if (!localCert.HasPrivateKey)
  556. {
  557. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  558. return null;
  559. }
  560. return localCert;
  561. }
  562. catch (Exception ex)
  563. {
  564. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  565. return null;
  566. }
  567. }
  568. /// <summary>
  569. /// Dirty hacks.
  570. /// </summary>
  571. private void SetStaticProperties()
  572. {
  573. // For now there's no real way to inject these properly
  574. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  575. BaseItem.ConfigurationManager = ServerConfigurationManager;
  576. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  577. BaseItem.ProviderManager = Resolve<IProviderManager>();
  578. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  579. BaseItem.ItemRepository = Resolve<IItemRepository>();
  580. BaseItem.FileSystem = _fileSystemManager;
  581. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  582. BaseItem.ChannelManager = Resolve<IChannelManager>();
  583. Video.LiveTvManager = Resolve<ILiveTvManager>();
  584. Folder.UserViewManager = Resolve<IUserViewManager>();
  585. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  586. UserView.CollectionManager = Resolve<ICollectionManager>();
  587. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  588. CollectionFolder.XmlSerializer = _xmlSerializer;
  589. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  590. CollectionFolder.ApplicationHost = this;
  591. }
  592. /// <summary>
  593. /// Finds plugin components and register them with the appropriate services.
  594. /// </summary>
  595. private void FindParts()
  596. {
  597. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  598. {
  599. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  600. ConfigurationManager.SaveConfiguration();
  601. }
  602. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  603. _plugins = GetExports<IPlugin>()
  604. .Select(LoadPlugin)
  605. .Where(i => i != null)
  606. .ToArray();
  607. if (Plugins != null)
  608. {
  609. var pluginBuilder = new StringBuilder();
  610. foreach (var plugin in Plugins)
  611. {
  612. pluginBuilder.Append(plugin.Name)
  613. .Append(' ')
  614. .Append(plugin.Version)
  615. .AppendLine();
  616. }
  617. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  618. }
  619. _urlPrefixes = GetUrlPrefixes().ToArray();
  620. _webSocketManager.Init(GetExports<IWebSocketListener>());
  621. Resolve<ILibraryManager>().AddParts(
  622. GetExports<IResolverIgnoreRule>(),
  623. GetExports<IItemResolver>(),
  624. GetExports<IIntroProvider>(),
  625. GetExports<IBaseItemComparer>(),
  626. GetExports<ILibraryPostScanTask>());
  627. Resolve<IProviderManager>().AddParts(
  628. GetExports<IImageProvider>(),
  629. GetExports<IMetadataService>(),
  630. GetExports<IMetadataProvider>(),
  631. GetExports<IMetadataSaver>(),
  632. GetExports<IExternalId>());
  633. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  634. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  635. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  636. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  637. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  638. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  639. }
  640. private IPlugin LoadPlugin(IPlugin plugin)
  641. {
  642. try
  643. {
  644. plugin.RegisterServices(ServiceCollection);
  645. }
  646. catch (Exception ex)
  647. {
  648. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  649. return null;
  650. }
  651. return plugin;
  652. }
  653. /// <summary>
  654. /// Discovers the types.
  655. /// </summary>
  656. protected void DiscoverTypes()
  657. {
  658. Logger.LogInformation("Loading assemblies");
  659. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  660. }
  661. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  662. {
  663. foreach (var ass in assemblies)
  664. {
  665. Type[] exportedTypes;
  666. try
  667. {
  668. exportedTypes = ass.GetExportedTypes();
  669. try
  670. {
  671. Type reg = (Type)exportedTypes.Where(p => string.Equals(p.Name, "PluginRegistration", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
  672. if (reg != null)
  673. {
  674. var pluginRegistration = Activator.CreateInstance(reg);
  675. reg.InvokeMember("RegisterServices", BindingFlags.InvokeMethod, null, pluginRegistration, new object[] { ServiceCollection }, CultureInfo.InvariantCulture);
  676. }
  677. }
  678. catch (Exception ex)
  679. {
  680. Logger.LogError(ex, "Error registering {Assembly} with D.I.", ass.FullName);
  681. continue;
  682. }
  683. }
  684. catch (FileNotFoundException ex)
  685. {
  686. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  687. continue;
  688. }
  689. catch (TypeLoadException ex)
  690. {
  691. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  692. continue;
  693. }
  694. foreach (Type type in exportedTypes)
  695. {
  696. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  697. {
  698. yield return type;
  699. }
  700. }
  701. }
  702. }
  703. private CertificateInfo CertificateInfo { get; set; }
  704. public X509Certificate2 Certificate { get; private set; }
  705. private IEnumerable<string> GetUrlPrefixes()
  706. {
  707. var hosts = new[] { "+" };
  708. return hosts.SelectMany(i =>
  709. {
  710. var prefixes = new List<string>
  711. {
  712. "http://" + i + ":" + HttpPort + "/"
  713. };
  714. if (CertificateInfo != null)
  715. {
  716. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  717. }
  718. return prefixes;
  719. });
  720. }
  721. /// <summary>
  722. /// Called when [configuration updated].
  723. /// </summary>
  724. /// <param name="sender">The sender.</param>
  725. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  726. protected void OnConfigurationUpdated(object sender, EventArgs e)
  727. {
  728. var requiresRestart = false;
  729. // Don't do anything if these haven't been set yet
  730. if (HttpPort != 0 && HttpsPort != 0)
  731. {
  732. // Need to restart if ports have changed
  733. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  734. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  735. {
  736. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  737. {
  738. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  739. ServerConfigurationManager.SaveConfiguration();
  740. requiresRestart = true;
  741. }
  742. }
  743. }
  744. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  745. {
  746. requiresRestart = true;
  747. }
  748. var currentCertPath = CertificateInfo?.Path;
  749. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  750. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  751. {
  752. requiresRestart = true;
  753. }
  754. if (requiresRestart)
  755. {
  756. Logger.LogInformation("App needs to be restarted due to configuration change.");
  757. NotifyPendingRestart();
  758. }
  759. }
  760. /// <summary>
  761. /// Notifies that the kernel that a change has been made that requires a restart.
  762. /// </summary>
  763. public void NotifyPendingRestart()
  764. {
  765. Logger.LogInformation("App needs to be restarted.");
  766. var changed = !HasPendingRestart;
  767. HasPendingRestart = true;
  768. if (changed)
  769. {
  770. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  771. }
  772. }
  773. /// <summary>
  774. /// Restarts this instance.
  775. /// </summary>
  776. public void Restart()
  777. {
  778. if (!CanSelfRestart)
  779. {
  780. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  781. }
  782. if (IsShuttingDown)
  783. {
  784. return;
  785. }
  786. IsShuttingDown = true;
  787. Task.Run(async () =>
  788. {
  789. try
  790. {
  791. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  792. }
  793. catch (Exception ex)
  794. {
  795. Logger.LogError(ex, "Error sending server restart notification");
  796. }
  797. Logger.LogInformation("Calling RestartInternal");
  798. RestartInternal();
  799. });
  800. }
  801. protected abstract void RestartInternal();
  802. /// <summary>
  803. /// Comparison function used in <see cref="GetPlugins" />.
  804. /// </summary>
  805. /// <param name="a">Item to compare.</param>
  806. /// <param name="b">Item to compare with.</param>
  807. /// <returns>Boolean result of the operation.</returns>
  808. private static int VersionCompare(
  809. (Version PluginVersion, string Name, string Path) a,
  810. (Version PluginVersion, string Name, string Path) b)
  811. {
  812. int compare = string.Compare(a.Name, b.Name, true, CultureInfo.InvariantCulture);
  813. if (compare == 0)
  814. {
  815. return a.PluginVersion.CompareTo(b.PluginVersion);
  816. }
  817. return compare;
  818. }
  819. /// <summary>
  820. /// Returns a list of plugins to install.
  821. /// </summary>
  822. /// <param name="path">Path to check.</param>
  823. /// <param name="cleanup">True if an attempt should be made to delete old plugs.</param>
  824. /// <returns>Enumerable list of dlls to load.</returns>
  825. private IEnumerable<string> GetPlugins(string path, bool cleanup = true)
  826. {
  827. var dllList = new List<string>();
  828. var versions = new List<(Version PluginVersion, string Name, string Path)>();
  829. var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
  830. string metafile;
  831. foreach (var dir in directories)
  832. {
  833. try
  834. {
  835. metafile = Path.Combine(dir, "meta.json");
  836. if (File.Exists(metafile))
  837. {
  838. var manifest = _jsonSerializer.DeserializeFromFile<PluginManifest>(metafile);
  839. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  840. {
  841. targetAbi = new Version(0, 0, 0, 1);
  842. }
  843. if (!Version.TryParse(manifest.Version, out var version))
  844. {
  845. version = new Version(0, 0, 0, 1);
  846. }
  847. if (ApplicationVersion >= targetAbi)
  848. {
  849. // Only load Plugins if the plugin is built for this version or below.
  850. versions.Add((version, manifest.Name, dir));
  851. }
  852. }
  853. else
  854. {
  855. // No metafile, so lets see if the folder is versioned.
  856. metafile = dir.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)[^1];
  857. int versionIndex = dir.LastIndexOf('_');
  858. if (versionIndex != -1 && Version.TryParse(dir.Substring(versionIndex + 1), out Version ver))
  859. {
  860. // Versioned folder.
  861. versions.Add((ver, metafile, dir));
  862. }
  863. else
  864. {
  865. // Un-versioned folder - Add it under the path name and version 0.0.0.1.
  866. versions.Add((new Version(0, 0, 0, 1), metafile, dir));
  867. }
  868. }
  869. }
  870. catch
  871. {
  872. continue;
  873. }
  874. }
  875. string lastName = string.Empty;
  876. versions.Sort(VersionCompare);
  877. // Traverse backwards through the list.
  878. // The first item will be the latest version.
  879. for (int x = versions.Count - 1; x >= 0; x--)
  880. {
  881. if (!string.Equals(lastName, versions[x].Name, StringComparison.OrdinalIgnoreCase))
  882. {
  883. dllList.AddRange(Directory.EnumerateFiles(versions[x].Path, "*.dll", SearchOption.AllDirectories));
  884. lastName = versions[x].Name;
  885. continue;
  886. }
  887. if (!string.IsNullOrEmpty(lastName) && cleanup)
  888. {
  889. // Attempt a cleanup of old folders.
  890. try
  891. {
  892. Logger.LogDebug("Deleting {Path}", versions[x].Path);
  893. Directory.Delete(versions[x].Path, true);
  894. }
  895. catch (Exception e)
  896. {
  897. Logger.LogWarning(e, "Unable to delete {Path}", versions[x].Path);
  898. }
  899. }
  900. }
  901. return dllList;
  902. }
  903. /// <summary>
  904. /// Gets the composable part assemblies.
  905. /// </summary>
  906. /// <returns>IEnumerable{Assembly}.</returns>
  907. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  908. {
  909. if (Directory.Exists(ApplicationPaths.PluginsPath))
  910. {
  911. foreach (var file in GetPlugins(ApplicationPaths.PluginsPath))
  912. {
  913. Assembly plugAss;
  914. try
  915. {
  916. plugAss = Assembly.LoadFrom(file);
  917. }
  918. catch (FileLoadException ex)
  919. {
  920. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  921. continue;
  922. }
  923. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  924. yield return plugAss;
  925. }
  926. }
  927. // Include composable parts in the Model assembly
  928. yield return typeof(SystemInfo).Assembly;
  929. // Include composable parts in the Common assembly
  930. yield return typeof(IApplicationHost).Assembly;
  931. // Include composable parts in the Controller assembly
  932. yield return typeof(IServerApplicationHost).Assembly;
  933. // Include composable parts in the Providers assembly
  934. yield return typeof(ProviderUtils).Assembly;
  935. // Include composable parts in the Photos assembly
  936. yield return typeof(PhotoProvider).Assembly;
  937. // Emby.Server implementations
  938. yield return typeof(InstallationManager).Assembly;
  939. // MediaEncoding
  940. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  941. // Local metadata
  942. yield return typeof(BoxSetXmlSaver).Assembly;
  943. // Notifications
  944. yield return typeof(NotificationManager).Assembly;
  945. // Xbmc
  946. yield return typeof(ArtistNfoProvider).Assembly;
  947. foreach (var i in GetAssembliesWithPartsInternal())
  948. {
  949. yield return i;
  950. }
  951. }
  952. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  953. /// <summary>
  954. /// Gets the system status.
  955. /// </summary>
  956. /// <param name="source">Where this request originated.</param>
  957. /// <returns>SystemInfo.</returns>
  958. public SystemInfo GetSystemInfo(IPAddress source)
  959. {
  960. return new SystemInfo
  961. {
  962. HasPendingRestart = HasPendingRestart,
  963. IsShuttingDown = IsShuttingDown,
  964. Version = ApplicationVersionString,
  965. WebSocketPortNumber = HttpPort,
  966. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  967. Id = SystemId,
  968. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  969. WebPath = ApplicationPaths.WebPath,
  970. LogPath = ApplicationPaths.LogDirectoryPath,
  971. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  972. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  973. CachePath = ApplicationPaths.CachePath,
  974. OperatingSystem = OperatingSystem.Id.ToString(),
  975. OperatingSystemDisplayName = OperatingSystem.Name,
  976. CanSelfRestart = CanSelfRestart,
  977. CanLaunchWebBrowser = CanLaunchWebBrowser,
  978. HasUpdateAvailable = HasUpdateAvailable,
  979. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  980. ServerName = FriendlyName,
  981. LocalAddress = GetSmartApiUrl(source),
  982. SupportsLibraryMonitor = true,
  983. EncoderLocation = _mediaEncoder.EncoderLocation,
  984. SystemArchitecture = RuntimeInformation.OSArchitecture,
  985. PackageName = _startupOptions.PackageName
  986. };
  987. }
  988. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  989. => NetManager.GetMacAddresses()
  990. .Select(i => new WakeOnLanInfo(i))
  991. .ToList();
  992. public PublicSystemInfo GetPublicSystemInfo(IPAddress source)
  993. {
  994. return new PublicSystemInfo
  995. {
  996. Version = ApplicationVersionString,
  997. ProductName = ApplicationProductName,
  998. Id = SystemId,
  999. OperatingSystem = OperatingSystem.Id.ToString(),
  1000. ServerName = FriendlyName,
  1001. LocalAddress = GetSmartApiUrl(source),
  1002. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  1003. };
  1004. }
  1005. /// <inheritdoc/>
  1006. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps;
  1007. /// <inheritdoc/>
  1008. public string GetSmartApiUrl(IPAddress ipAddress, int? port = null)
  1009. {
  1010. // Published server ends with a /
  1011. if (_startupOptions.PublishedServerUrl != null)
  1012. {
  1013. // Published server ends with a '/', so we need to remove it.
  1014. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1015. }
  1016. string smart = NetManager.GetBindInterface(ipAddress, out port);
  1017. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1018. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1019. {
  1020. return smart.Trim('/');
  1021. }
  1022. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1023. }
  1024. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  1025. {
  1026. // Published server ends with a /
  1027. if (_startupOptions.PublishedServerUrl != null)
  1028. {
  1029. // Published server ends with a '/', so we need to remove it.
  1030. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1031. }
  1032. string smart = NetManager.GetBindInterface(request, out port);
  1033. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1034. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1035. {
  1036. return smart.Trim('/');
  1037. }
  1038. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  1039. }
  1040. public string GetSmartApiUrl(string hostname, int? port = null)
  1041. {
  1042. // Published server ends with a /
  1043. if (_startupOptions.PublishedServerUrl != null)
  1044. {
  1045. // Published server ends with a '/', so we need to remove it.
  1046. return _startupOptions.PublishedServerUrl.ToString().Trim('/');
  1047. }
  1048. string smart = NetManager.GetBindInterface(hostname, out port);
  1049. // If the smartAPI doesn't start with http then treat it as a host or ip.
  1050. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  1051. {
  1052. return smart.Trim('/');
  1053. }
  1054. return GetLocalApiUrl(smart.Trim('/'), null, port);
  1055. }
  1056. /// <inheritdoc/>
  1057. public string GetLoopbackHttpApiUrl()
  1058. {
  1059. if (NetManager.IsIP6Enabled)
  1060. {
  1061. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  1062. }
  1063. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  1064. }
  1065. /// <inheritdoc/>
  1066. public string GetLocalApiUrl(string host, string scheme = null, int? port = null)
  1067. {
  1068. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  1069. // not. For consistency, always trim the trailing slash.
  1070. return new UriBuilder
  1071. {
  1072. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  1073. Host = host,
  1074. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  1075. Path = ServerConfigurationManager.Configuration.BaseUrl
  1076. }.ToString().TrimEnd('/');
  1077. }
  1078. /// <summary>
  1079. /// Gets the servers friendly name.
  1080. /// </summary>
  1081. public string FriendlyName =>
  1082. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1083. ? Environment.MachineName
  1084. : ServerConfigurationManager.Configuration.ServerName;
  1085. /// <summary>
  1086. /// Shuts down.
  1087. /// </summary>
  1088. public async Task Shutdown()
  1089. {
  1090. if (IsShuttingDown)
  1091. {
  1092. return;
  1093. }
  1094. IsShuttingDown = true;
  1095. try
  1096. {
  1097. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1098. }
  1099. catch (Exception ex)
  1100. {
  1101. Logger.LogError(ex, "Error sending server shutdown notification");
  1102. }
  1103. ShutdownInternal();
  1104. }
  1105. protected abstract void ShutdownInternal();
  1106. public event EventHandler HasUpdateAvailableChanged;
  1107. private bool _hasUpdateAvailable;
  1108. public bool HasUpdateAvailable
  1109. {
  1110. get => _hasUpdateAvailable;
  1111. set
  1112. {
  1113. var fireEvent = value && !_hasUpdateAvailable;
  1114. _hasUpdateAvailable = value;
  1115. if (fireEvent)
  1116. {
  1117. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1118. }
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// Removes the plugin.
  1123. /// </summary>
  1124. /// <param name="plugin">The plugin.</param>
  1125. public void RemovePlugin(IPlugin plugin)
  1126. {
  1127. var list = _plugins.ToList();
  1128. list.Remove(plugin);
  1129. _plugins = list.ToArray();
  1130. }
  1131. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1132. {
  1133. var assemblies = _allConcreteTypes
  1134. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1135. .Select(i => i.Assembly)
  1136. .Distinct();
  1137. foreach (var assembly in assemblies)
  1138. {
  1139. Logger.LogDebug("Found API endpoints in plugin {name}", assembly.FullName);
  1140. yield return assembly;
  1141. }
  1142. }
  1143. public virtual void LaunchUrl(string url)
  1144. {
  1145. if (!CanLaunchWebBrowser)
  1146. {
  1147. throw new NotSupportedException();
  1148. }
  1149. var process = new Process
  1150. {
  1151. StartInfo = new ProcessStartInfo
  1152. {
  1153. FileName = url,
  1154. UseShellExecute = true,
  1155. ErrorDialog = false
  1156. },
  1157. EnableRaisingEvents = true
  1158. };
  1159. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1160. try
  1161. {
  1162. process.Start();
  1163. }
  1164. catch (Exception ex)
  1165. {
  1166. Logger.LogError(ex, "Error launching url: {url}", url);
  1167. throw;
  1168. }
  1169. }
  1170. private bool _disposed = false;
  1171. /// <summary>
  1172. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1173. /// </summary>
  1174. public void Dispose()
  1175. {
  1176. Dispose(true);
  1177. GC.SuppressFinalize(this);
  1178. }
  1179. /// <summary>
  1180. /// Releases unmanaged and - optionally - managed resources.
  1181. /// </summary>
  1182. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1183. protected virtual void Dispose(bool dispose)
  1184. {
  1185. if (_disposed)
  1186. {
  1187. return;
  1188. }
  1189. if (dispose)
  1190. {
  1191. var type = GetType();
  1192. Logger.LogInformation("Disposing {Type}", type.Name);
  1193. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1194. _disposableParts.Clear();
  1195. foreach (var part in parts)
  1196. {
  1197. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1198. try
  1199. {
  1200. part.Dispose();
  1201. }
  1202. catch (Exception ex)
  1203. {
  1204. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1205. }
  1206. }
  1207. }
  1208. _disposed = true;
  1209. }
  1210. }
  1211. internal class CertificateInfo
  1212. {
  1213. public string Path { get; set; }
  1214. public string Password { get; set; }
  1215. }
  1216. }