ApplicationHost.cs 66 KB

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