ApplicationHost.cs 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Sockets;
  12. using System.Reflection;
  13. using System.Runtime.InteropServices;
  14. using System.Security.Cryptography.X509Certificates;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using Emby.Dlna;
  19. using Emby.Dlna.Main;
  20. using Emby.Dlna.Ssdp;
  21. using Emby.Drawing;
  22. using Emby.Notifications;
  23. using Emby.Photos;
  24. using Emby.Server.Implementations.Activity;
  25. using Emby.Server.Implementations.Archiving;
  26. using Emby.Server.Implementations.Channels;
  27. using Emby.Server.Implementations.Collections;
  28. using Emby.Server.Implementations.Configuration;
  29. using Emby.Server.Implementations.Cryptography;
  30. using Emby.Server.Implementations.Data;
  31. using Emby.Server.Implementations.Devices;
  32. using Emby.Server.Implementations.Diagnostics;
  33. using Emby.Server.Implementations.Dto;
  34. using Emby.Server.Implementations.HttpServer;
  35. using Emby.Server.Implementations.HttpServer.Security;
  36. using Emby.Server.Implementations.IO;
  37. using Emby.Server.Implementations.Library;
  38. using Emby.Server.Implementations.LiveTv;
  39. using Emby.Server.Implementations.Localization;
  40. using Emby.Server.Implementations.Net;
  41. using Emby.Server.Implementations.Playlists;
  42. using Emby.Server.Implementations.ScheduledTasks;
  43. using Emby.Server.Implementations.Security;
  44. using Emby.Server.Implementations.Serialization;
  45. using Emby.Server.Implementations.Services;
  46. using Emby.Server.Implementations.Session;
  47. using Emby.Server.Implementations.SocketSharp;
  48. using Emby.Server.Implementations.TV;
  49. using Emby.Server.Implementations.Updates;
  50. using MediaBrowser.Api;
  51. using MediaBrowser.Common;
  52. using MediaBrowser.Common.Configuration;
  53. using MediaBrowser.Common.Events;
  54. using MediaBrowser.Common.Net;
  55. using MediaBrowser.Common.Plugins;
  56. using MediaBrowser.Common.Updates;
  57. using MediaBrowser.Controller;
  58. using MediaBrowser.Controller.Authentication;
  59. using MediaBrowser.Controller.Channels;
  60. using MediaBrowser.Controller.Chapters;
  61. using MediaBrowser.Controller.Collections;
  62. using MediaBrowser.Controller.Configuration;
  63. using MediaBrowser.Controller.Devices;
  64. using MediaBrowser.Controller.Dlna;
  65. using MediaBrowser.Controller.Drawing;
  66. using MediaBrowser.Controller.Dto;
  67. using MediaBrowser.Controller.Entities;
  68. using MediaBrowser.Controller.Library;
  69. using MediaBrowser.Controller.LiveTv;
  70. using MediaBrowser.Controller.MediaEncoding;
  71. using MediaBrowser.Controller.Net;
  72. using MediaBrowser.Controller.Notifications;
  73. using MediaBrowser.Controller.Persistence;
  74. using MediaBrowser.Controller.Playlists;
  75. using MediaBrowser.Controller.Plugins;
  76. using MediaBrowser.Controller.Providers;
  77. using MediaBrowser.Controller.Resolvers;
  78. using MediaBrowser.Controller.Security;
  79. using MediaBrowser.Controller.Session;
  80. using MediaBrowser.Controller.Sorting;
  81. using MediaBrowser.Controller.Subtitles;
  82. using MediaBrowser.Controller.TV;
  83. using MediaBrowser.LocalMetadata.Savers;
  84. using MediaBrowser.MediaEncoding.BdInfo;
  85. using MediaBrowser.Model.Activity;
  86. using MediaBrowser.Model.Configuration;
  87. using MediaBrowser.Model.Cryptography;
  88. using MediaBrowser.Model.Diagnostics;
  89. using MediaBrowser.Model.Dlna;
  90. using MediaBrowser.Model.Events;
  91. using MediaBrowser.Model.Globalization;
  92. using MediaBrowser.Model.IO;
  93. using MediaBrowser.Model.MediaInfo;
  94. using MediaBrowser.Model.Net;
  95. using MediaBrowser.Model.Serialization;
  96. using MediaBrowser.Model.Services;
  97. using MediaBrowser.Model.System;
  98. using MediaBrowser.Model.Tasks;
  99. using MediaBrowser.Model.Updates;
  100. using MediaBrowser.Providers.Chapters;
  101. using MediaBrowser.Providers.Manager;
  102. using MediaBrowser.Providers.Plugins.TheTvdb;
  103. using MediaBrowser.Providers.Subtitles;
  104. using MediaBrowser.WebDashboard.Api;
  105. using MediaBrowser.XbmcMetadata.Providers;
  106. using Microsoft.AspNetCore.Http;
  107. using Microsoft.AspNetCore.Http.Extensions;
  108. using Microsoft.Extensions.Configuration;
  109. using Microsoft.Extensions.DependencyInjection;
  110. using Microsoft.Extensions.Logging;
  111. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  112. namespace Emby.Server.Implementations
  113. {
  114. /// <summary>
  115. /// Class CompositionRoot.
  116. /// </summary>
  117. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  118. {
  119. private SqliteUserRepository _userRepository;
  120. private SqliteDisplayPreferencesRepository _displayPreferencesRepository;
  121. private IChannelManager _channelManager;
  122. private ISessionManager _sessionManager;
  123. private ILiveTvManager _liveTvManager;
  124. private INotificationManager _notificationManager;
  125. private IHttpServer _httpServer;
  126. /// <summary>
  127. /// Gets a value indicating whether this instance can self restart.
  128. /// </summary>
  129. /// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
  130. public abstract bool CanSelfRestart { get; }
  131. public virtual bool CanLaunchWebBrowser
  132. {
  133. get
  134. {
  135. if (!Environment.UserInteractive)
  136. {
  137. return false;
  138. }
  139. if (StartupOptions.IsService)
  140. {
  141. return false;
  142. }
  143. if (OperatingSystem.Id == OperatingSystemId.Windows
  144. || OperatingSystem.Id == OperatingSystemId.Darwin)
  145. {
  146. return true;
  147. }
  148. return false;
  149. }
  150. }
  151. /// <summary>
  152. /// Occurs when [has pending restart changed].
  153. /// </summary>
  154. public event EventHandler HasPendingRestartChanged;
  155. /// <summary>
  156. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  157. /// </summary>
  158. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  159. public bool HasPendingRestart { get; private set; }
  160. /// <inheritdoc />
  161. public bool IsShuttingDown { get; private set; }
  162. /// <summary>
  163. /// Gets the logger.
  164. /// </summary>
  165. protected ILogger Logger { get; }
  166. private IPlugin[] _plugins;
  167. /// <summary>
  168. /// Gets the plugins.
  169. /// </summary>
  170. /// <value>The plugins.</value>
  171. public IReadOnlyList<IPlugin> Plugins => _plugins;
  172. /// <summary>
  173. /// Gets the logger factory.
  174. /// </summary>
  175. protected ILoggerFactory LoggerFactory { get; }
  176. /// <summary>
  177. /// Gets or sets the application paths.
  178. /// </summary>
  179. /// <value>The application paths.</value>
  180. protected ServerApplicationPaths ApplicationPaths { get; set; }
  181. /// <summary>
  182. /// Gets or sets all concrete types.
  183. /// </summary>
  184. /// <value>All concrete types.</value>
  185. private Type[] _allConcreteTypes;
  186. /// <summary>
  187. /// The disposable parts.
  188. /// </summary>
  189. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  190. /// <summary>
  191. /// Gets the configuration manager.
  192. /// </summary>
  193. /// <value>The configuration manager.</value>
  194. protected IConfigurationManager ConfigurationManager { get; set; }
  195. public IFileSystem FileSystemManager { get; set; }
  196. /// <inheritdoc />
  197. public PackageVersionClass SystemUpdateLevel
  198. {
  199. get
  200. {
  201. #if BETA
  202. return PackageVersionClass.Beta;
  203. #else
  204. return PackageVersionClass.Release;
  205. #endif
  206. }
  207. }
  208. /// <summary>
  209. /// Gets or sets the service provider.
  210. /// </summary>
  211. public IServiceProvider ServiceProvider { get; set; }
  212. /// <summary>
  213. /// Gets the http port for the webhost.
  214. /// </summary>
  215. public int HttpPort { get; private set; }
  216. /// <summary>
  217. /// Gets the https port for the webhost.
  218. /// </summary>
  219. public int HttpsPort { get; private set; }
  220. /// <summary>
  221. /// Gets the server configuration manager.
  222. /// </summary>
  223. /// <value>The server configuration manager.</value>
  224. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  225. /// <summary>
  226. /// Gets or sets the user manager.
  227. /// </summary>
  228. /// <value>The user manager.</value>
  229. public IUserManager UserManager { get; set; }
  230. /// <summary>
  231. /// Gets or sets the library manager.
  232. /// </summary>
  233. /// <value>The library manager.</value>
  234. internal ILibraryManager LibraryManager { get; set; }
  235. /// <summary>
  236. /// Gets or sets the directory watchers.
  237. /// </summary>
  238. /// <value>The directory watchers.</value>
  239. private ILibraryMonitor LibraryMonitor { get; set; }
  240. /// <summary>
  241. /// Gets or sets the provider manager.
  242. /// </summary>
  243. /// <value>The provider manager.</value>
  244. private IProviderManager ProviderManager { get; set; }
  245. public IImageProcessor ImageProcessor { get; set; }
  246. /// <summary>
  247. /// Gets or sets the media encoder.
  248. /// </summary>
  249. /// <value>The media encoder.</value>
  250. private IMediaEncoder MediaEncoder { get; set; }
  251. public LocalizationManager LocalizationManager { get; set; }
  252. /// <summary>
  253. /// Gets or sets the user data repository.
  254. /// </summary>
  255. /// <value>The user data repository.</value>
  256. private IUserDataManager UserDataManager { get; set; }
  257. internal SqliteItemRepository ItemRepository { get; set; }
  258. private ISubtitleManager SubtitleManager { get; set; }
  259. private IDeviceManager DeviceManager { get; set; }
  260. private IAuthenticationRepository AuthenticationRepository { get; set; }
  261. private ITVSeriesManager TVSeriesManager { get; set; }
  262. private IMediaSourceManager MediaSourceManager { get; set; }
  263. /// <summary>
  264. /// Gets the installation manager.
  265. /// </summary>
  266. /// <value>The installation manager.</value>
  267. protected IInstallationManager InstallationManager { get; private set; }
  268. public IStartupOptions StartupOptions { get; }
  269. internal IImageEncoder ImageEncoder { get; private set; }
  270. protected IProcessFactory ProcessFactory { get; private set; }
  271. protected readonly IXmlSerializer XmlSerializer;
  272. protected ISocketFactory SocketFactory { get; private set; }
  273. protected ITaskManager TaskManager { get; private set; }
  274. public IHttpClient HttpClient { get; private set; }
  275. protected INetworkManager NetworkManager { get; set; }
  276. public IJsonSerializer JsonSerializer { get; private set; }
  277. protected IIsoManager IsoManager { get; private set; }
  278. /// <summary>
  279. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  280. /// </summary>
  281. public ApplicationHost(
  282. ServerApplicationPaths applicationPaths,
  283. ILoggerFactory loggerFactory,
  284. IStartupOptions options,
  285. IFileSystem fileSystem,
  286. IImageEncoder imageEncoder,
  287. INetworkManager networkManager)
  288. {
  289. XmlSerializer = new MyXmlSerializer();
  290. NetworkManager = networkManager;
  291. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  292. ApplicationPaths = applicationPaths;
  293. LoggerFactory = loggerFactory;
  294. FileSystemManager = fileSystem;
  295. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, XmlSerializer, FileSystemManager);
  296. Logger = LoggerFactory.CreateLogger("App");
  297. StartupOptions = options;
  298. ImageEncoder = imageEncoder;
  299. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  300. NetworkManager.NetworkChanged += OnNetworkChanged;
  301. }
  302. public string ExpandVirtualPath(string path)
  303. {
  304. var appPaths = ApplicationPaths;
  305. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  306. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  307. }
  308. public string ReverseVirtualPath(string path)
  309. {
  310. var appPaths = ApplicationPaths;
  311. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  312. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  313. }
  314. private string[] GetConfiguredLocalSubnets()
  315. {
  316. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  317. }
  318. private void OnNetworkChanged(object sender, EventArgs e)
  319. {
  320. _validAddressResults.Clear();
  321. }
  322. /// <inheritdoc />
  323. public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version;
  324. /// <inheritdoc />
  325. public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  326. /// <summary>
  327. /// Gets the current application user agent.
  328. /// </summary>
  329. /// <value>The application user agent.</value>
  330. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  331. /// <summary>
  332. /// Gets the email address for use within a comment section of a user agent field.
  333. /// Presently used to provide contact information to MusicBrainz service.
  334. /// </summary>
  335. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  336. /// <summary>
  337. /// Gets the current application name.
  338. /// </summary>
  339. /// <value>The application name.</value>
  340. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  341. private DeviceId _deviceId;
  342. public string SystemId
  343. {
  344. get
  345. {
  346. if (_deviceId == null)
  347. {
  348. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  349. }
  350. return _deviceId.Value;
  351. }
  352. }
  353. /// <summary>
  354. /// Gets the name.
  355. /// </summary>
  356. /// <value>The name.</value>
  357. public string Name => ApplicationProductName;
  358. /// <summary>
  359. /// Creates an instance of type and resolves all constructor dependencies.
  360. /// </summary>
  361. /// <param name="type">The type.</param>
  362. /// <returns>System.Object.</returns>
  363. public object CreateInstance(Type type)
  364. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  365. /// <summary>
  366. /// Creates an instance of type and resolves all constructor dependencies.
  367. /// </summary>
  368. /// /// <typeparam name="T">The type.</typeparam>
  369. /// <returns>T.</returns>
  370. public T CreateInstance<T>()
  371. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  372. /// <summary>
  373. /// Creates the instance safe.
  374. /// </summary>
  375. /// <param name="type">The type.</param>
  376. /// <returns>System.Object.</returns>
  377. protected object CreateInstanceSafe(Type type)
  378. {
  379. try
  380. {
  381. Logger.LogDebug("Creating instance of {Type}", type);
  382. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  383. }
  384. catch (Exception ex)
  385. {
  386. Logger.LogError(ex, "Error creating {Type}", type);
  387. return null;
  388. }
  389. }
  390. /// <summary>
  391. /// Resolves this instance.
  392. /// </summary>
  393. /// <typeparam name="T">The type</typeparam>
  394. /// <returns>``0.</returns>
  395. public T Resolve<T>() => ServiceProvider.GetService<T>();
  396. /// <summary>
  397. /// Gets the export types.
  398. /// </summary>
  399. /// <typeparam name="T">The type.</typeparam>
  400. /// <returns>IEnumerable{Type}.</returns>
  401. public IEnumerable<Type> GetExportTypes<T>()
  402. {
  403. var currentType = typeof(T);
  404. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  405. }
  406. /// <inheritdoc />
  407. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  408. {
  409. // Convert to list so this isn't executed for each iteration
  410. var parts = GetExportTypes<T>()
  411. .Select(CreateInstanceSafe)
  412. .Where(i => i != null)
  413. .Cast<T>()
  414. .ToList();
  415. if (manageLifetime)
  416. {
  417. lock (_disposableParts)
  418. {
  419. _disposableParts.AddRange(parts.OfType<IDisposable>());
  420. }
  421. }
  422. return parts;
  423. }
  424. /// <summary>
  425. /// Runs the startup tasks.
  426. /// </summary>
  427. /// <returns><see cref="Task" />.</returns>
  428. public async Task RunStartupTasksAsync()
  429. {
  430. Logger.LogInformation("Running startup tasks");
  431. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  432. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  433. MediaEncoder.SetFFmpegPath();
  434. Logger.LogInformation("ServerId: {0}", SystemId);
  435. var entryPoints = GetExports<IServerEntryPoint>();
  436. var stopWatch = new Stopwatch();
  437. stopWatch.Start();
  438. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  439. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  440. Logger.LogInformation("Core startup complete");
  441. _httpServer.GlobalResponse = null;
  442. stopWatch.Restart();
  443. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  444. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  445. stopWatch.Stop();
  446. }
  447. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  448. {
  449. foreach (var entryPoint in entryPoints)
  450. {
  451. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  452. {
  453. continue;
  454. }
  455. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  456. yield return entryPoint.RunAsync();
  457. }
  458. }
  459. /// <inheritdoc/>
  460. public async Task InitAsync(IServiceCollection serviceCollection, IConfiguration startupConfig)
  461. {
  462. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  463. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  464. // Safeguard against invalid configuration
  465. if (HttpPort == HttpsPort)
  466. {
  467. HttpPort = ServerConfiguration.DefaultHttpPort;
  468. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  469. }
  470. JsonSerializer = new JsonSerializer();
  471. if (Plugins != null)
  472. {
  473. var pluginBuilder = new StringBuilder();
  474. foreach (var plugin in Plugins)
  475. {
  476. pluginBuilder.AppendLine(
  477. string.Format(
  478. CultureInfo.InvariantCulture,
  479. "{0} {1}",
  480. plugin.Name,
  481. plugin.Version));
  482. }
  483. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  484. }
  485. DiscoverTypes();
  486. await RegisterServices(serviceCollection, startupConfig).ConfigureAwait(false);
  487. }
  488. public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  489. {
  490. if (!context.WebSockets.IsWebSocketRequest)
  491. {
  492. await next().ConfigureAwait(false);
  493. return;
  494. }
  495. await _httpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  496. }
  497. public async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  498. {
  499. if (context.WebSockets.IsWebSocketRequest)
  500. {
  501. await next().ConfigureAwait(false);
  502. return;
  503. }
  504. var request = context.Request;
  505. var response = context.Response;
  506. var localPath = context.Request.Path.ToString();
  507. var req = new WebSocketSharpRequest(request, response, request.Path, LoggerFactory.CreateLogger<WebSocketSharpRequest>());
  508. await _httpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  509. }
  510. /// <summary>
  511. /// Registers services/resources with the service collection that will be available via DI.
  512. /// </summary>
  513. protected async Task RegisterServices(IServiceCollection serviceCollection, IConfiguration startupConfig)
  514. {
  515. serviceCollection.AddMemoryCache();
  516. serviceCollection.AddSingleton(ConfigurationManager);
  517. serviceCollection.AddSingleton<IApplicationHost>(this);
  518. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  519. serviceCollection.AddSingleton(JsonSerializer);
  520. // TODO: Support for injecting ILogger should be deprecated in favour of ILogger<T> and this removed
  521. serviceCollection.AddSingleton<ILogger>(Logger);
  522. serviceCollection.AddSingleton(FileSystemManager);
  523. serviceCollection.AddSingleton<TvdbClientManager>();
  524. HttpClient = new HttpClientManager.HttpClientManager(
  525. ApplicationPaths,
  526. LoggerFactory.CreateLogger<HttpClientManager.HttpClientManager>(),
  527. FileSystemManager,
  528. () => ApplicationUserAgent);
  529. serviceCollection.AddSingleton(HttpClient);
  530. serviceCollection.AddSingleton(NetworkManager);
  531. IsoManager = new IsoManager();
  532. serviceCollection.AddSingleton(IsoManager);
  533. TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LoggerFactory, FileSystemManager);
  534. serviceCollection.AddSingleton(TaskManager);
  535. serviceCollection.AddSingleton(XmlSerializer);
  536. ProcessFactory = new ProcessFactory();
  537. serviceCollection.AddSingleton(ProcessFactory);
  538. serviceCollection.AddSingleton(typeof(IStreamHelper), typeof(StreamHelper));
  539. var cryptoProvider = new CryptographyProvider();
  540. serviceCollection.AddSingleton<ICryptoProvider>(cryptoProvider);
  541. SocketFactory = new SocketFactory();
  542. serviceCollection.AddSingleton(SocketFactory);
  543. serviceCollection.AddSingleton(typeof(IInstallationManager), typeof(InstallationManager));
  544. serviceCollection.AddSingleton(typeof(IZipClient), typeof(ZipClient));
  545. serviceCollection.AddSingleton(typeof(IHttpResultFactory), typeof(HttpResultFactory));
  546. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  547. serviceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  548. serviceCollection.AddSingleton(ServerConfigurationManager);
  549. LocalizationManager = new LocalizationManager(ServerConfigurationManager, JsonSerializer, LoggerFactory.CreateLogger<LocalizationManager>());
  550. await LocalizationManager.LoadAll().ConfigureAwait(false);
  551. serviceCollection.AddSingleton<ILocalizationManager>(LocalizationManager);
  552. serviceCollection.AddSingleton<IBlurayExaminer>(new BdInfoExaminer(FileSystemManager));
  553. UserDataManager = new UserDataManager(LoggerFactory, ServerConfigurationManager, () => UserManager);
  554. serviceCollection.AddSingleton(UserDataManager);
  555. _displayPreferencesRepository = new SqliteDisplayPreferencesRepository(
  556. LoggerFactory.CreateLogger<SqliteDisplayPreferencesRepository>(),
  557. ApplicationPaths,
  558. FileSystemManager);
  559. serviceCollection.AddSingleton<IDisplayPreferencesRepository>(_displayPreferencesRepository);
  560. ItemRepository = new SqliteItemRepository(ServerConfigurationManager, this, LoggerFactory.CreateLogger<SqliteItemRepository>(), LocalizationManager);
  561. serviceCollection.AddSingleton<IItemRepository>(ItemRepository);
  562. AuthenticationRepository = GetAuthenticationRepository();
  563. serviceCollection.AddSingleton(AuthenticationRepository);
  564. _userRepository = GetUserRepository();
  565. UserManager = new UserManager(
  566. LoggerFactory.CreateLogger<UserManager>(),
  567. _userRepository,
  568. XmlSerializer,
  569. NetworkManager,
  570. () => ImageProcessor,
  571. Resolve<IDtoService>,
  572. this,
  573. JsonSerializer,
  574. FileSystemManager,
  575. cryptoProvider);
  576. serviceCollection.AddSingleton(UserManager);
  577. MediaEncoder = new MediaBrowser.MediaEncoding.Encoder.MediaEncoder(
  578. LoggerFactory.CreateLogger<MediaBrowser.MediaEncoding.Encoder.MediaEncoder>(),
  579. ServerConfigurationManager,
  580. FileSystemManager,
  581. ProcessFactory,
  582. LocalizationManager,
  583. Resolve<ISubtitleEncoder>,
  584. startupConfig,
  585. StartupOptions.FFmpegPath);
  586. serviceCollection.AddSingleton(MediaEncoder);
  587. LibraryManager = new LibraryManager(this, LoggerFactory, TaskManager, UserManager, ServerConfigurationManager, UserDataManager, () => LibraryMonitor, FileSystemManager, () => ProviderManager, Resolve<IUserViewManager>, MediaEncoder);
  588. serviceCollection.AddSingleton(LibraryManager);
  589. var musicManager = new MusicManager(LibraryManager);
  590. serviceCollection.AddSingleton<IMusicManager>(musicManager);
  591. LibraryMonitor = new LibraryMonitor(LoggerFactory, LibraryManager, ServerConfigurationManager, FileSystemManager);
  592. serviceCollection.AddSingleton(LibraryMonitor);
  593. serviceCollection.AddSingleton<ISearchEngine>(new SearchEngine(LoggerFactory, LibraryManager, UserManager));
  594. CertificateInfo = GetCertificateInfo(true);
  595. Certificate = GetCertificate(CertificateInfo);
  596. serviceCollection.AddSingleton<ServiceController>();
  597. serviceCollection.AddSingleton<IHttpListener, WebSocketSharpListener>();
  598. serviceCollection.AddSingleton<IHttpServer, HttpListenerHost>();
  599. ImageProcessor = new ImageProcessor(LoggerFactory.CreateLogger<ImageProcessor>(), ServerConfigurationManager.ApplicationPaths, FileSystemManager, ImageEncoder, () => LibraryManager, () => MediaEncoder);
  600. serviceCollection.AddSingleton(ImageProcessor);
  601. TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager);
  602. serviceCollection.AddSingleton(TVSeriesManager);
  603. DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager);
  604. serviceCollection.AddSingleton(DeviceManager);
  605. MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory, JsonSerializer, FileSystemManager, UserDataManager, () => MediaEncoder);
  606. serviceCollection.AddSingleton(MediaSourceManager);
  607. SubtitleManager = new SubtitleManager(LoggerFactory, FileSystemManager, LibraryMonitor, MediaSourceManager, LocalizationManager);
  608. serviceCollection.AddSingleton(SubtitleManager);
  609. ProviderManager = new ProviderManager(HttpClient, SubtitleManager, ServerConfigurationManager, LibraryMonitor, LoggerFactory, FileSystemManager, ApplicationPaths, () => LibraryManager, JsonSerializer);
  610. serviceCollection.AddSingleton(ProviderManager);
  611. // TODO: Refactor to eliminate circular dependency here so Lazy<> isn't required
  612. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  613. serviceCollection.AddSingleton<IDtoService, DtoService>();
  614. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  615. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  616. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  617. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  618. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  619. serviceCollection.AddSingleton<LiveTvDtoService>();
  620. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  621. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  622. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  623. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  624. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  625. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  626. serviceCollection.AddSingleton<IActivityRepository, ActivityRepository>();
  627. serviceCollection.AddSingleton<IActivityManager, ActivityManager>();
  628. serviceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  629. serviceCollection.AddSingleton<ISessionContext, SessionContext>();
  630. serviceCollection.AddSingleton<IAuthService, AuthService>();
  631. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  632. serviceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  633. serviceCollection.AddSingleton<EncodingHelper>();
  634. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  635. }
  636. /// <summary>
  637. /// Create services registered with the service container that need to be initialized at application startup.
  638. /// </summary>
  639. public void InitializeServices()
  640. {
  641. _channelManager = Resolve<IChannelManager>();
  642. _sessionManager = Resolve<ISessionManager>();
  643. _liveTvManager = Resolve<ILiveTvManager>();
  644. _notificationManager = Resolve<INotificationManager>();
  645. _httpServer = Resolve<IHttpServer>();
  646. ((ActivityRepository)Resolve<IActivityRepository>()).Initialize();
  647. _displayPreferencesRepository.Initialize();
  648. var userDataRepo = new SqliteUserDataRepository(LoggerFactory.CreateLogger<SqliteUserDataRepository>(), ApplicationPaths);
  649. SetStaticProperties();
  650. ((UserManager)UserManager).Initialize();
  651. ((UserDataManager)UserDataManager).Repository = userDataRepo;
  652. ItemRepository.Initialize(userDataRepo, UserManager);
  653. ((LibraryManager)LibraryManager).ItemRepository = ItemRepository;
  654. }
  655. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  656. {
  657. // Distinct these to prevent users from reporting problems that aren't actually problems
  658. var commandLineArgs = Environment
  659. .GetCommandLineArgs()
  660. .Distinct();
  661. // Get all 'JELLYFIN_' prefixed environment variables
  662. var allEnvVars = Environment.GetEnvironmentVariables();
  663. var jellyfinEnvVars = new Dictionary<object, object>();
  664. foreach (var key in allEnvVars.Keys)
  665. {
  666. if (key.ToString().StartsWith("JELLYFIN_", StringComparison.OrdinalIgnoreCase))
  667. {
  668. jellyfinEnvVars.Add(key, allEnvVars[key]);
  669. }
  670. }
  671. logger.LogInformation("Environment Variables: {EnvVars}", jellyfinEnvVars);
  672. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  673. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  674. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  675. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  676. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  677. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  678. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  679. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  680. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  681. }
  682. private X509Certificate2 GetCertificate(CertificateInfo info)
  683. {
  684. var certificateLocation = info?.Path;
  685. if (string.IsNullOrWhiteSpace(certificateLocation))
  686. {
  687. return null;
  688. }
  689. try
  690. {
  691. if (!File.Exists(certificateLocation))
  692. {
  693. return null;
  694. }
  695. // Don't use an empty string password
  696. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  697. var localCert = new X509Certificate2(certificateLocation, password);
  698. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  699. if (!localCert.HasPrivateKey)
  700. {
  701. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  702. return null;
  703. }
  704. return localCert;
  705. }
  706. catch (Exception ex)
  707. {
  708. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  709. return null;
  710. }
  711. }
  712. /// <summary>
  713. /// Gets the user repository.
  714. /// </summary>
  715. /// <returns><see cref="Task{SqliteUserRepository}" />.</returns>
  716. private SqliteUserRepository GetUserRepository()
  717. {
  718. var repo = new SqliteUserRepository(
  719. LoggerFactory.CreateLogger<SqliteUserRepository>(),
  720. ApplicationPaths);
  721. repo.Initialize();
  722. return repo;
  723. }
  724. private IAuthenticationRepository GetAuthenticationRepository()
  725. {
  726. var repo = new AuthenticationRepository(LoggerFactory, ServerConfigurationManager);
  727. repo.Initialize();
  728. return repo;
  729. }
  730. /// <summary>
  731. /// Dirty hacks.
  732. /// </summary>
  733. private void SetStaticProperties()
  734. {
  735. ItemRepository.ImageProcessor = ImageProcessor;
  736. // For now there's no real way to inject these properly
  737. BaseItem.Logger = LoggerFactory.CreateLogger("BaseItem");
  738. BaseItem.ConfigurationManager = ServerConfigurationManager;
  739. BaseItem.LibraryManager = LibraryManager;
  740. BaseItem.ProviderManager = ProviderManager;
  741. BaseItem.LocalizationManager = LocalizationManager;
  742. BaseItem.ItemRepository = ItemRepository;
  743. User.UserManager = UserManager;
  744. BaseItem.FileSystem = FileSystemManager;
  745. BaseItem.UserDataManager = UserDataManager;
  746. BaseItem.ChannelManager = _channelManager;
  747. Video.LiveTvManager = _liveTvManager;
  748. Folder.UserViewManager = Resolve<IUserViewManager>();
  749. UserView.TVSeriesManager = TVSeriesManager;
  750. UserView.CollectionManager = Resolve<ICollectionManager>();
  751. BaseItem.MediaSourceManager = MediaSourceManager;
  752. CollectionFolder.XmlSerializer = XmlSerializer;
  753. CollectionFolder.JsonSerializer = JsonSerializer;
  754. CollectionFolder.ApplicationHost = this;
  755. AuthenticatedAttribute.AuthService = Resolve<IAuthService>();
  756. }
  757. private async void PluginInstalled(object sender, GenericEventArgs<PackageVersionInfo> args)
  758. {
  759. string dir = Path.Combine(ApplicationPaths.PluginsPath, args.Argument.name);
  760. var types = Directory.EnumerateFiles(dir, "*.dll", SearchOption.AllDirectories)
  761. .Select(Assembly.LoadFrom)
  762. .SelectMany(x => x.ExportedTypes)
  763. .Where(x => x.IsClass && !x.IsAbstract && !x.IsInterface && !x.IsGenericType)
  764. .ToArray();
  765. int oldLen = _allConcreteTypes.Length;
  766. Array.Resize(ref _allConcreteTypes, oldLen + types.Length);
  767. types.CopyTo(_allConcreteTypes, oldLen);
  768. var plugins = types.Where(x => x.IsAssignableFrom(typeof(IPlugin)))
  769. .Select(CreateInstanceSafe)
  770. .Where(x => x != null)
  771. .Cast<IPlugin>()
  772. .Select(LoadPlugin)
  773. .Where(x => x != null)
  774. .ToArray();
  775. oldLen = _plugins.Length;
  776. Array.Resize(ref _plugins, oldLen + plugins.Length);
  777. plugins.CopyTo(_plugins, oldLen);
  778. var entries = types.Where(x => x.IsAssignableFrom(typeof(IServerEntryPoint)))
  779. .Select(CreateInstanceSafe)
  780. .Where(x => x != null)
  781. .Cast<IServerEntryPoint>()
  782. .ToList();
  783. await Task.WhenAll(StartEntryPoints(entries, true)).ConfigureAwait(false);
  784. await Task.WhenAll(StartEntryPoints(entries, false)).ConfigureAwait(false);
  785. }
  786. /// <summary>
  787. /// Finds the parts.
  788. /// </summary>
  789. public void FindParts()
  790. {
  791. InstallationManager = ServiceProvider.GetService<IInstallationManager>();
  792. InstallationManager.PluginInstalled += PluginInstalled;
  793. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  794. {
  795. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  796. ConfigurationManager.SaveConfiguration();
  797. }
  798. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  799. _plugins = GetExports<IPlugin>()
  800. .Select(LoadPlugin)
  801. .Where(i => i != null)
  802. .ToArray();
  803. _httpServer.Init(GetExportTypes<IService>(), GetExports<IWebSocketListener>(), GetUrlPrefixes());
  804. LibraryManager.AddParts(
  805. GetExports<IResolverIgnoreRule>(),
  806. GetExports<IItemResolver>(),
  807. GetExports<IIntroProvider>(),
  808. GetExports<IBaseItemComparer>(),
  809. GetExports<ILibraryPostScanTask>());
  810. ProviderManager.AddParts(
  811. GetExports<IImageProvider>(),
  812. GetExports<IMetadataService>(),
  813. GetExports<IMetadataProvider>(),
  814. GetExports<IMetadataSaver>(),
  815. GetExports<IExternalId>());
  816. _liveTvManager.AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  817. SubtitleManager.AddParts(GetExports<ISubtitleProvider>());
  818. _channelManager.AddParts(GetExports<IChannel>());
  819. MediaSourceManager.AddParts(GetExports<IMediaSourceProvider>());
  820. _notificationManager.AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  821. UserManager.AddParts(GetExports<IAuthenticationProvider>(), GetExports<IPasswordResetProvider>());
  822. IsoManager.AddParts(GetExports<IIsoMounter>());
  823. }
  824. private IPlugin LoadPlugin(IPlugin plugin)
  825. {
  826. try
  827. {
  828. if (plugin is IPluginAssembly assemblyPlugin)
  829. {
  830. var assembly = plugin.GetType().Assembly;
  831. var assemblyName = assembly.GetName();
  832. var assemblyFilePath = assembly.Location;
  833. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  834. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  835. try
  836. {
  837. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  838. if (idAttributes.Length > 0)
  839. {
  840. var attribute = (GuidAttribute)idAttributes[0];
  841. var assemblyId = new Guid(attribute.Value);
  842. assemblyPlugin.SetId(assemblyId);
  843. }
  844. }
  845. catch (Exception ex)
  846. {
  847. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  848. }
  849. }
  850. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  851. {
  852. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  853. }
  854. }
  855. catch (Exception ex)
  856. {
  857. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  858. return null;
  859. }
  860. return plugin;
  861. }
  862. /// <summary>
  863. /// Discovers the types.
  864. /// </summary>
  865. protected void DiscoverTypes()
  866. {
  867. Logger.LogInformation("Loading assemblies");
  868. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  869. }
  870. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  871. {
  872. foreach (var ass in assemblies)
  873. {
  874. Type[] exportedTypes;
  875. try
  876. {
  877. exportedTypes = ass.GetExportedTypes();
  878. }
  879. catch (FileNotFoundException ex)
  880. {
  881. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  882. continue;
  883. }
  884. foreach (Type type in exportedTypes)
  885. {
  886. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  887. {
  888. yield return type;
  889. }
  890. }
  891. }
  892. }
  893. private CertificateInfo CertificateInfo { get; set; }
  894. public X509Certificate2 Certificate { get; private set; }
  895. private IEnumerable<string> GetUrlPrefixes()
  896. {
  897. var hosts = new[] { "+" };
  898. return hosts.SelectMany(i =>
  899. {
  900. var prefixes = new List<string>
  901. {
  902. "http://" + i + ":" + HttpPort + "/"
  903. };
  904. if (CertificateInfo != null)
  905. {
  906. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  907. }
  908. return prefixes;
  909. });
  910. }
  911. private CertificateInfo GetCertificateInfo(bool generateCertificate)
  912. {
  913. // Custom cert
  914. return new CertificateInfo
  915. {
  916. Path = ServerConfigurationManager.Configuration.CertificatePath,
  917. Password = ServerConfigurationManager.Configuration.CertificatePassword
  918. };
  919. }
  920. /// <summary>
  921. /// Called when [configuration updated].
  922. /// </summary>
  923. /// <param name="sender">The sender.</param>
  924. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  925. protected void OnConfigurationUpdated(object sender, EventArgs e)
  926. {
  927. var requiresRestart = false;
  928. // Don't do anything if these haven't been set yet
  929. if (HttpPort != 0 && HttpsPort != 0)
  930. {
  931. // Need to restart if ports have changed
  932. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  933. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  934. {
  935. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  936. {
  937. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  938. ServerConfigurationManager.SaveConfiguration();
  939. requiresRestart = true;
  940. }
  941. }
  942. }
  943. if (!_httpServer.UrlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  944. {
  945. requiresRestart = true;
  946. }
  947. var currentCertPath = CertificateInfo?.Path;
  948. var newCertInfo = GetCertificateInfo(false);
  949. var newCertPath = newCertInfo?.Path;
  950. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  951. {
  952. requiresRestart = true;
  953. }
  954. if (requiresRestart)
  955. {
  956. Logger.LogInformation("App needs to be restarted due to configuration change.");
  957. NotifyPendingRestart();
  958. }
  959. }
  960. /// <summary>
  961. /// Notifies that the kernel that a change has been made that requires a restart
  962. /// </summary>
  963. public void NotifyPendingRestart()
  964. {
  965. Logger.LogInformation("App needs to be restarted.");
  966. var changed = !HasPendingRestart;
  967. HasPendingRestart = true;
  968. if (changed)
  969. {
  970. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  971. }
  972. }
  973. /// <summary>
  974. /// Restarts this instance.
  975. /// </summary>
  976. public void Restart()
  977. {
  978. if (!CanSelfRestart)
  979. {
  980. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  981. }
  982. if (IsShuttingDown)
  983. {
  984. return;
  985. }
  986. IsShuttingDown = true;
  987. Task.Run(async () =>
  988. {
  989. try
  990. {
  991. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  992. }
  993. catch (Exception ex)
  994. {
  995. Logger.LogError(ex, "Error sending server restart notification");
  996. }
  997. Logger.LogInformation("Calling RestartInternal");
  998. RestartInternal();
  999. });
  1000. }
  1001. protected abstract void RestartInternal();
  1002. /// <summary>
  1003. /// Gets the composable part assemblies.
  1004. /// </summary>
  1005. /// <returns>IEnumerable{Assembly}.</returns>
  1006. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  1007. {
  1008. if (Directory.Exists(ApplicationPaths.PluginsPath))
  1009. {
  1010. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  1011. {
  1012. Assembly plugAss;
  1013. try
  1014. {
  1015. plugAss = Assembly.LoadFrom(file);
  1016. }
  1017. catch (FileLoadException ex)
  1018. {
  1019. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  1020. continue;
  1021. }
  1022. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  1023. yield return plugAss;
  1024. }
  1025. }
  1026. // Include composable parts in the Api assembly
  1027. yield return typeof(ApiEntryPoint).Assembly;
  1028. // Include composable parts in the Dashboard assembly
  1029. yield return typeof(DashboardService).Assembly;
  1030. // Include composable parts in the Model assembly
  1031. yield return typeof(SystemInfo).Assembly;
  1032. // Include composable parts in the Common assembly
  1033. yield return typeof(IApplicationHost).Assembly;
  1034. // Include composable parts in the Controller assembly
  1035. yield return typeof(IServerApplicationHost).Assembly;
  1036. // Include composable parts in the Providers assembly
  1037. yield return typeof(ProviderUtils).Assembly;
  1038. // Include composable parts in the Photos assembly
  1039. yield return typeof(PhotoProvider).Assembly;
  1040. // Emby.Server implementations
  1041. yield return typeof(InstallationManager).Assembly;
  1042. // MediaEncoding
  1043. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  1044. // Dlna
  1045. yield return typeof(DlnaEntryPoint).Assembly;
  1046. // Local metadata
  1047. yield return typeof(BoxSetXmlSaver).Assembly;
  1048. // Notifications
  1049. yield return typeof(NotificationManager).Assembly;
  1050. // Xbmc
  1051. yield return typeof(ArtistNfoProvider).Assembly;
  1052. foreach (var i in GetAssembliesWithPartsInternal())
  1053. {
  1054. yield return i;
  1055. }
  1056. }
  1057. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  1058. /// <summary>
  1059. /// Gets the system status.
  1060. /// </summary>
  1061. /// <param name="cancellationToken">The cancellation token.</param>
  1062. /// <returns>SystemInfo.</returns>
  1063. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  1064. {
  1065. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1066. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  1067. return new SystemInfo
  1068. {
  1069. HasPendingRestart = HasPendingRestart,
  1070. IsShuttingDown = IsShuttingDown,
  1071. Version = ApplicationVersionString,
  1072. WebSocketPortNumber = HttpPort,
  1073. CompletedInstallations = InstallationManager.CompletedInstallations.ToArray(),
  1074. Id = SystemId,
  1075. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  1076. WebPath = ApplicationPaths.WebPath,
  1077. LogPath = ApplicationPaths.LogDirectoryPath,
  1078. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  1079. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  1080. CachePath = ApplicationPaths.CachePath,
  1081. HttpServerPortNumber = HttpPort,
  1082. SupportsHttps = SupportsHttps,
  1083. HttpsPortNumber = HttpsPort,
  1084. OperatingSystem = OperatingSystem.Id.ToString(),
  1085. OperatingSystemDisplayName = OperatingSystem.Name,
  1086. CanSelfRestart = CanSelfRestart,
  1087. CanLaunchWebBrowser = CanLaunchWebBrowser,
  1088. HasUpdateAvailable = HasUpdateAvailable,
  1089. TranscodingTempPath = transcodingTempPath,
  1090. ServerName = FriendlyName,
  1091. LocalAddress = localAddress,
  1092. SupportsLibraryMonitor = true,
  1093. EncoderLocation = MediaEncoder.EncoderLocation,
  1094. SystemArchitecture = RuntimeInformation.OSArchitecture,
  1095. SystemUpdateLevel = SystemUpdateLevel,
  1096. PackageName = StartupOptions.PackageName
  1097. };
  1098. }
  1099. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  1100. => NetworkManager.GetMacAddresses()
  1101. .Select(i => new WakeOnLanInfo(i))
  1102. .ToList();
  1103. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  1104. {
  1105. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  1106. return new PublicSystemInfo
  1107. {
  1108. Version = ApplicationVersionString,
  1109. ProductName = ApplicationProductName,
  1110. Id = SystemId,
  1111. OperatingSystem = OperatingSystem.Id.ToString(),
  1112. ServerName = FriendlyName,
  1113. LocalAddress = localAddress
  1114. };
  1115. }
  1116. public bool EnableHttps => SupportsHttps && ServerConfigurationManager.Configuration.EnableHttps;
  1117. public bool SupportsHttps => Certificate != null || ServerConfigurationManager.Configuration.IsBehindProxy;
  1118. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  1119. {
  1120. try
  1121. {
  1122. // Return the first matched address, if found, or the first known local address
  1123. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  1124. foreach (var address in addresses)
  1125. {
  1126. return GetLocalApiUrl(address);
  1127. }
  1128. return null;
  1129. }
  1130. catch (Exception ex)
  1131. {
  1132. Logger.LogError(ex, "Error getting local Ip address information");
  1133. }
  1134. return null;
  1135. }
  1136. /// <summary>
  1137. /// Removes the scope id from IPv6 addresses.
  1138. /// </summary>
  1139. /// <param name="address">The IPv6 address.</param>
  1140. /// <returns>The IPv6 address without the scope id.</returns>
  1141. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  1142. {
  1143. var index = address.IndexOf('%');
  1144. if (index == -1)
  1145. {
  1146. return address;
  1147. }
  1148. return address.Slice(0, index);
  1149. }
  1150. /// <inheritdoc />
  1151. public string GetLocalApiUrl(IPAddress ipAddress)
  1152. {
  1153. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  1154. {
  1155. var str = RemoveScopeId(ipAddress.ToString());
  1156. Span<char> span = new char[str.Length + 2];
  1157. span[0] = '[';
  1158. str.CopyTo(span.Slice(1));
  1159. span[^1] = ']';
  1160. return GetLocalApiUrl(span);
  1161. }
  1162. return GetLocalApiUrl(ipAddress.ToString());
  1163. }
  1164. /// <inheritdoc />
  1165. public string GetLocalApiUrl(ReadOnlySpan<char> host)
  1166. {
  1167. var url = new StringBuilder(64);
  1168. url.Append(EnableHttps ? "https://" : "http://")
  1169. .Append(host)
  1170. .Append(':')
  1171. .Append(EnableHttps ? HttpsPort : HttpPort);
  1172. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1173. if (baseUrl.Length != 0)
  1174. {
  1175. url.Append(baseUrl);
  1176. }
  1177. return url.ToString();
  1178. }
  1179. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1180. {
  1181. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1182. }
  1183. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1184. {
  1185. var addresses = ServerConfigurationManager
  1186. .Configuration
  1187. .LocalNetworkAddresses
  1188. .Select(NormalizeConfiguredLocalAddress)
  1189. .Where(i => i != null)
  1190. .ToList();
  1191. if (addresses.Count == 0)
  1192. {
  1193. addresses.AddRange(NetworkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1194. }
  1195. var resultList = new List<IPAddress>();
  1196. foreach (var address in addresses)
  1197. {
  1198. if (!allowLoopback)
  1199. {
  1200. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1201. {
  1202. continue;
  1203. }
  1204. }
  1205. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1206. if (valid)
  1207. {
  1208. resultList.Add(address);
  1209. if (limit > 0 && resultList.Count >= limit)
  1210. {
  1211. return resultList;
  1212. }
  1213. }
  1214. }
  1215. return resultList;
  1216. }
  1217. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1218. {
  1219. var index = address.Trim('/').IndexOf('/');
  1220. if (index != -1)
  1221. {
  1222. address = address.Substring(index + 1);
  1223. }
  1224. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1225. {
  1226. return result;
  1227. }
  1228. return null;
  1229. }
  1230. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1231. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1232. {
  1233. if (address.Equals(IPAddress.Loopback)
  1234. || address.Equals(IPAddress.IPv6Loopback))
  1235. {
  1236. return true;
  1237. }
  1238. var apiUrl = GetLocalApiUrl(address);
  1239. apiUrl += "/system/ping";
  1240. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1241. {
  1242. return cachedResult;
  1243. }
  1244. try
  1245. {
  1246. using (var response = await HttpClient.SendAsync(
  1247. new HttpRequestOptions
  1248. {
  1249. Url = apiUrl,
  1250. LogErrorResponseBody = false,
  1251. BufferContent = false,
  1252. CancellationToken = cancellationToken
  1253. }, HttpMethod.Post).ConfigureAwait(false))
  1254. {
  1255. using (var reader = new StreamReader(response.Content))
  1256. {
  1257. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1258. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1259. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1260. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1261. return valid;
  1262. }
  1263. }
  1264. }
  1265. catch (OperationCanceledException)
  1266. {
  1267. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1268. throw;
  1269. }
  1270. catch (Exception ex)
  1271. {
  1272. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1273. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1274. return false;
  1275. }
  1276. }
  1277. public string FriendlyName =>
  1278. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1279. ? Environment.MachineName
  1280. : ServerConfigurationManager.Configuration.ServerName;
  1281. /// <summary>
  1282. /// Shuts down.
  1283. /// </summary>
  1284. public async Task Shutdown()
  1285. {
  1286. if (IsShuttingDown)
  1287. {
  1288. return;
  1289. }
  1290. IsShuttingDown = true;
  1291. try
  1292. {
  1293. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1294. }
  1295. catch (Exception ex)
  1296. {
  1297. Logger.LogError(ex, "Error sending server shutdown notification");
  1298. }
  1299. ShutdownInternal();
  1300. }
  1301. protected abstract void ShutdownInternal();
  1302. public event EventHandler HasUpdateAvailableChanged;
  1303. private bool _hasUpdateAvailable;
  1304. public bool HasUpdateAvailable
  1305. {
  1306. get => _hasUpdateAvailable;
  1307. set
  1308. {
  1309. var fireEvent = value && !_hasUpdateAvailable;
  1310. _hasUpdateAvailable = value;
  1311. if (fireEvent)
  1312. {
  1313. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1314. }
  1315. }
  1316. }
  1317. /// <summary>
  1318. /// Removes the plugin.
  1319. /// </summary>
  1320. /// <param name="plugin">The plugin.</param>
  1321. public void RemovePlugin(IPlugin plugin)
  1322. {
  1323. var list = _plugins.ToList();
  1324. list.Remove(plugin);
  1325. _plugins = list.ToArray();
  1326. }
  1327. public virtual void LaunchUrl(string url)
  1328. {
  1329. if (!CanLaunchWebBrowser)
  1330. {
  1331. throw new NotSupportedException();
  1332. }
  1333. var process = ProcessFactory.Create(new ProcessOptions
  1334. {
  1335. FileName = url,
  1336. EnableRaisingEvents = true,
  1337. UseShellExecute = true,
  1338. ErrorDialog = false
  1339. });
  1340. process.Exited += ProcessExited;
  1341. try
  1342. {
  1343. process.Start();
  1344. }
  1345. catch (Exception ex)
  1346. {
  1347. Logger.LogError(ex, "Error launching url: {url}", url);
  1348. throw;
  1349. }
  1350. }
  1351. private static void ProcessExited(object sender, EventArgs e)
  1352. {
  1353. ((IProcess)sender).Dispose();
  1354. }
  1355. public virtual void EnableLoopback(string appName)
  1356. {
  1357. }
  1358. private bool _disposed = false;
  1359. /// <summary>
  1360. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1361. /// </summary>
  1362. public void Dispose()
  1363. {
  1364. Dispose(true);
  1365. GC.SuppressFinalize(this);
  1366. }
  1367. /// <summary>
  1368. /// Releases unmanaged and - optionally - managed resources.
  1369. /// </summary>
  1370. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1371. protected virtual void Dispose(bool dispose)
  1372. {
  1373. if (_disposed)
  1374. {
  1375. return;
  1376. }
  1377. if (dispose)
  1378. {
  1379. var type = GetType();
  1380. Logger.LogInformation("Disposing {Type}", type.Name);
  1381. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1382. _disposableParts.Clear();
  1383. foreach (var part in parts)
  1384. {
  1385. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1386. try
  1387. {
  1388. part.Dispose();
  1389. }
  1390. catch (Exception ex)
  1391. {
  1392. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1393. }
  1394. }
  1395. _userRepository?.Dispose();
  1396. _displayPreferencesRepository?.Dispose();
  1397. }
  1398. _userRepository = null;
  1399. _displayPreferencesRepository = null;
  1400. _disposed = true;
  1401. }
  1402. }
  1403. internal class CertificateInfo
  1404. {
  1405. public string Path { get; set; }
  1406. public string Password { get; set; }
  1407. }
  1408. }