ApplicationHost.cs 67 KB

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