ApplicationHost.cs 65 KB

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